//菜谱管理
angular.module('SmartCanteenApp.cookbookManage', ['ngRoute', 'ngTouch'])

    .config(['$routeProvider', function ($routeProvider) {
         $routeProvider.when('/dishesSetup', {
            templateUrl: 'cookbookManage/dishesSetup.html',
            controller: 'dishesSetupCtrl'
        });
        $routeProvider.when('/dishEdit/:dishId/:categoryId', {
            templateUrl: 'cookbookManage/dishEdit.html',
            controller: 'dishEditCtrl'
        });
         $routeProvider.when('/menuTemplate', {
            templateUrl: 'cookbookManage/menuTemplate.html',
            controller: 'menuTemplateCtrl'
        });
         $routeProvider.when('/templateEdit/:tempId/:tempName', {
            templateUrl: 'cookbookManage/templateEdit.html',
            controller: 'templateEditCtrl'
        });
         $routeProvider.when('/dishPublish', {
            templateUrl: 'cookbookManage/dishPublish.html',
            controller: 'dishPublishCtrl'
        });//IntelligencePublish.html
        $routeProvider.when('/intelPublish', {
            templateUrl: 'cookbookManage/IntelligencePublish.html',
            controller: 'intelPublishCtrl'
        });
        $routeProvider.when('/login', {
            templateUrl: 'cookbookManage/angularlogin.html',
            controller: 'angularloginCtrl'
        });
         $routeProvider.when('/packageManage', {
            templateUrl: 'cookbookManage/packageManage.html',
            controller: 'packageManageCtrl'
        });
    }])
//菜品设置
   .controller('dishesSetupCtrl', ['$scope', '$timeout', function ($scope, $timeout) {
   	$(".modal-dialog").draggable();//为模态对话框添加拖拽
        $(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动
   	//获取食堂下所有分类
   			$scope.getCategorys = function(){
   				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/categorys",'',"GET",function(data){
				 			if( data.code == 0){
//				 				$scope.$applyAsync(function(){
				 					$scope.classify = data.data;  
//				 				});
//								$timeout(function(){
//									$scope.classify = data.data;  
//								},100);
				 			}else{
				 				console.log(data.msg);
				 			}
				 		});
   			}
   			//获取某食堂下所有菜品
   			$scope.getDishes = function(){
   				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/items",'',"GET",function(data){
				 			if( data.code == 0){
//				 				$scope.$applyAsync(function(){
				 					$scope.dishesInfors = data.data;  
				 					$scope.intial = $scope.dishesInfors.concat() ;
    								$scope.currentData = $scope.dishesInfors.concat() ;
//				 				});
//								$timeout(function(){
//									$scope.classify = data.data;  
//								},100);
				 			}else{
				 				console.log(data.msg);
				 			}
				 		});
   			}
   			
   			if( $scope.getCanteenId() != ''){
   				$scope.canteenId =  $scope.getCanteenId() ;
   				//获取某食堂下所有分类
		 		$scope.getCategorys();
		 		//获取所有菜品
		 		$scope.getDishes();
   			}
		   	$scope.$on('to-child', function(event,data) {
						 //获取从父控制器传来的当前选中食堂
						$scope.canteenId = data;
						//获取某食堂下所有分类
				 		$scope.getCategorys();
				 		//获取所有菜品
				 		$scope.getDishes();
				});
			$scope.selectDishId = '';
    		//选中某行后获取该行信息
			$scope.itemSelected = function(event,id){
				$scope.selectDishId = id;
	    		event.stopPropagation();
	    		//将数据展示区域的所有td背景颜色先去掉
	    		var allTd = document.getElementById('dataList').getElementsByTagName('td');
	    		for(var i = 0;i< allTd.length ; i++ ){
	    			allTd[i].className = '';
	    		}
	    		//保证js点击锁定的是tr标签
	    		var target = event.target ;
	    		if( target.nodeName == 'TD'){
	    			target = target.parentNode ;
	    		}
	    		var p = target.children ;
	    		for(var i = 0;i< p.length ; i++ ){
	    			p[i].className = 'selected';
	    		}
	    		$scope.id = p[0].innerHTML;//菜品id
	    		$scope.name = p[1].innerHTML;//菜品名称
	    		$scope.unit = p[2].innerHTML;//单位
	    		$scope.in_price = p[3].innerHTML;//内部价格
	    		$scope.out_price = p[4].innerHTML;//外部价格
	    		$scope.window = p[5].innerHTML;//售卖窗口
	    		$scope.chief = p[6].innerHTML;//厨师
	    		$scope.status = p[7].innerHTML;//状态
    	}
    		$scope.intial = [] ;
    		$scope.currentData = [] ;
    		 //实时监控搜索框的值
            $scope.$watch('cardInfor',  function() {
            	if($scope.cardInfor ==undefined){
            		$scope.cardInfor = '';
            	}
		           //准备一个空的数组
		           var newList = [];
		           var arr = $scope.currentData ;
		           var length = arr.length;
		           
		           	for(var i=0;i<length;i++){
						if(  arr[i].name.indexOf($scope.cardInfor) >= 0	){
							newList.push(arr[i]);
						}
		           }
		           $scope.dishesInfors = newList;
            });
            $scope.categoryId = 'all';
            $scope.categoryName = '全部类别';
            //点击全部类别
            $scope.allCategory = function(){
            	 $scope.dishesInfors =$scope.intial.concat() ;
            	 $scope.currentData = $scope.intial.concat() ;
            	  $scope.categoryId = '';
            	  $scope.categoryName = '';
            }
            //点击菜品类别
            $scope.choiceCategory = function(event,id,name){
            	
            	event.stopPropagation();
            	var category = name ;
            	$('.categories').each(function(){
	   				$(this).removeClass('selected');
	   			});
   				$('#category_'+id).addClass('selected');
            	
            	 //准备一个空的数组
		           var newList = [];
		           var arr = $scope.intial ;
		           var length = arr.length;
		           	for(var i=0;i<length;i++){
						if(  arr[i].category_id == id	){
							newList.push(arr[i]);
						}
		           }
			       $scope.currentData =  newList ;
			       $scope.categoryId = id;
			       $scope.categoryName = category;
			       $scope.selectDishId = '';
		           $scope.dishesInfors = newList;
            }
            //跳转至菜品新增页面
            $scope.addDish = function(){
            	//先判断是否点击行
        	   $scope.jump('/dishEdit/add/'+$scope.categoryId); 
            }
            //跳转至菜品修改页面
            $scope.updateDish = function(){
            	
            	//先判断是否点击行
//          	var selectedTds = document.getElementsByClassName('selected');
            	
        	   if( $scope.selectDishId =='' ){
        	   		$('#contentHtml').html('请选择一道菜品');
					$('#warningChoose').modal('toggle');
					return;
        	   }
        	   $scope.jump('/dishEdit/'+$scope.id+'/'+$scope.categoryId); 
            }
            //启用/停用某道菜品
            $scope.startEnd = function(){
//          	var selectedTds = document.getElementsByClassName('selected');
        	   if( $scope.selectDishId == ''){
        	   		$('#contentHtml').html('请选择一道菜品');
					$('#warningChoose').modal('toggle');
					return;
        	   }
        	   $scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/items/"+$scope.id+"/stop",'',"PUT",
          				function(data){
				 			if( data.code == 0){
				 				$scope.showSuccess('操作成功！');
								//获取所有菜品
						 		$scope.getDishes();
				 			}else{
				 				$scope.showError(data.msg);
				 			}
				 		});
            }
            //打开删除菜品模板
            $scope.delDish = function(){
//          	var selectedTds = document.getElementsByClassName('selected');
            	 if( $scope.selectDishId == ''){
        	   		$('#contentHtml').html('请选择一道菜品');
					$('#warningChoose').modal('toggle');
					return;
        	   }
            	 $("#delDish").modal('toggle')
            }
            //删除菜品
            $scope.del_dish = function(){
            	
            	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/items/"+$scope.id,'',"DELETE",
          				function(data){
				 			if( data.code == 0){
//				 				var arr = $scope.dishesInfors;
//	    						for(var i = 0;i<arr.length;i++){
//	    							if(arr[i].id == $scope.id){
//	    								$scope.dishesInfors.splice(i, 1);
//	    							}
//	    						}
									//获取某食堂下所有分类
							 		$scope.getCategorys();
							 		//获取所有菜品
							 		$scope.getDishes();
	    						 $("#delDish").modal('toggle');
				 			}else{
				 				$scope.showError(data.msg);
				 			}
				 		});
            }
            //打开新增模板
            $scope.addCategory = function(){
            	$scope.categoryName ='';
            	$scope.showIt = false;
            	$("#addCategory").modal('toggle');
            }
            //新增模板中，确定按钮
            $scope.addCategory_true = function(){
            	if($scope.categoryName == undefined || $scope.categoryName == ''){
            		$scope.categoryName = '';
            		$scope.showIt = true;
            		return;
            	}
            	if( $scope.categoryName.length > 10){
	           			$scope.showError('类别名称的长度不得大于10位');
	           			return;
	           		}
            	//类别名称有值后，调取后台新增分类方法
            	var postData = {"name": $scope.categoryName}
            	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/category",postData,"POST",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$scope.getCategorys();
			 				$("#addCategory").modal('toggle');
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
            	
            }
            //点击类别修改按钮
            $scope.updateCategory = function(){
            	if( $scope.categoryId == ''){
        			$('#contentHtml').html('请选择菜品类别');
					$('#warningChoose').modal('toggle');
					return;
            	}
            	$("#updateCategory").modal('toggle')
            }
          	//修改类别模板的确定按钮
          	$scope.updateCategory_true = function(){
          		if($scope.categoryName == undefined || $scope.categoryName == ''){
            		$scope.categoryName = '';
            		return;
            	}
          		if( $scope.categoryName.length > 10){
	           			$scope.showError('类别名称的长度不得大于10位');
	           			return;
	           		}
          		var putData = {"name": $scope.categoryName}
          		//调取后台修改分类方法
          		$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/categorys/"+$scope.categoryId,putData,"PUT",
          				function(data){
				 			if( data.code == 0){
				 				$scope.showSuccess('操作成功！');
				 				//修改成功后，调取重新好去所有分类，刷新页面
				 					$scope.getCategorys();
				 					 $("#updateCategory").modal('toggle');
				 			}else{
				 				$scope.showError(data.msg);
				 			}
				 		});
          	}
          	//点击类别删除按钮
          	$scope.delCategory = function(){
          		if( $scope.categoryId == ''){
        			$('#contentHtml').html('请选择菜品类别');
					$('#warningChoose').modal('toggle');
					return;
            	}
          		$("#delCategory").modal('toggle')
          	}
           	 //删除菜品类别
            $scope.del_category = function(){
            	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/categorys/"+$scope.categoryId,'',"DELETE",
          				function(data){
				 			if( data.code == 0){
				 				$scope.showSuccess('操作成功！');
				 				//删除成功后，调取重新好去所有分类，刷新页面
				 					$scope.getCategorys();
				 					 $("#delCategory").modal('toggle');
				 			}else{
				 				$scope.showError(data.msg);
				 			}
				 		});
            }
            //新增类别时，
            $scope.judgeShow = function(){
            	if( $scope.categoryName == '' || $scope.categoryName == undefined){
            		 $scope.showIt = true;
            	}else{
            		$scope.showIt = false;
            	}
            }
             //实时监控新增模板名称的值
            $scope.$watch('categoryName',  function() {
            	if($scope.categoryName != '' && $scope.categoryName !=undefined){
            		$scope.showIt = false;
            	}
            });
    }])
   
   //菜品编辑
   .controller('dishEditCtrl', ['$scope', '$timeout','$routeParams',function ($scope, $timeout,$routeParams) {
   	$(".modal-dialog").draggable();//为模态对话框添加拖拽
        $(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动
		$scope.dishId = $routeParams.dishId ;
		$scope.postCategoryId = $routeParams.categoryId ;
   		var t = $scope.tastes ;
   		var c = $scope.colors ;
   		var s = $scope.shapes ;
   		for( var i = 0;i<t.length ;i++){
   			t[i].checked = false;
   		}
   		for( var i = 0;i<c.length ;i++){
   			c[i].checked = false;
   		}
   		for( var i = 0;i<s.length ;i++){
   			s[i].checked = false;
   		}
   		
		//获取食堂下所有分类
		$scope.getCategorys = function(){
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/categorys",'',"GET",function(data){
			 			if( data.code == 0){
			 					$scope.categorys = data.data;
			 					if( $scope.postCategoryId == 'all'){
			 						if( $scope.categorys.length != 0){
			 							$scope.category_id = $scope.categorys[0].id ;
			 						}
			 					}else{
			 						$scope.category_id = $scope.postCategoryId ;
			 					}
			 			}else{
			 				console.log(data.msg);
			 			}
			 		});
		}
		//获取食堂下所有档口
		$scope.getWindows = function(){
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/base_system/canteens/"+$scope.canteenId+"/windows",'',"GET",function(data){
			 			if( data.code == 0){
			 					$scope.windows = data.data;
			 					if( $scope.windows[0] != undefined && $scope.windows[0] != null){
			 						$scope.window = $scope.windows[0].id;
			 					}
			 			}else{
			 				console.log(data.msg);
			 			}
			 		});
		}
		$scope.kanbanUnits = [];
		//获取所有单位
		$scope.getUnits = function(){
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/itemsUnit",'',"GET",function(data){
			 			if( data.code == 0){
			 					$scope.units = data.data;
			 					console.log($scope.units);
//			 					$scope.kanbanUnits = data.data;
			 					if( $scope.units.length != 0 && $scope.unitId != undefined){
			 						$scope.unitId = $scope.units[0].id;
			 						$scope.UnitName = $scope.units[0].name;
			 						var arr = $scope.units.concat();
			 						for( var i = 0; i<arr.length ; i++){
			 							if(arr[i].id == $scope.unitId){
			 								arr.splice(i,1);
			 							}
			 						}
			 						$scope.kanbanUnits = arr.concat();
//			 						//$scope.kanbanUnits = arr.splice($.inArray($scope.units[0],arr),1);
			 						$scope.kanbanUnitId = $scope.kanbanUnits[0].id;
			 						
			 					}
			 			}else{
			 				console.log(data.msg);
			 			}
			 		});
		}
		$scope.workshops = [];
		$scope.workTime = '0';
		//获取所有制作车间
		$scope.getWorkShops= function(){
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/base_system/canteens/"+$scope.canteenId+"/workshops",'',"GET",function(data){
						console.log(data);
			 			if( data.code == 0){
			 				$scope.workshops = data.data;
			 				console.log($scope.workshops);
			 				if($scope.workshops[0] != null && $scope.workshops[0] != undefined ){
			 					$scope.workshop_id = $scope.workshops[0].id;
			 				}
			 			}else{
			 				console.log(data.msg);
			 			}
			 		});
		}
		$scope.procedures = [];
		//获取所有制作工序
		$scope.getProcedures= function(){
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/product_plan/canteens/"+$scope.canteenId+"/procedures",'',"GET",function(data){
						console.log(data);
			 			if( data.code == 0){
			 				$scope.procedures = data.data;
			 				if($scope.procedures[0] != null && $scope.procedures[0] != undefined){
			 					$scope.procedure_id = $scope.procedures[0].id;
			 				}
			 			}else{
			 				console.log(data.msg);
			 			}
			 		});
		}
		$scope.materielsFenLei = [];
		$scope.sonsMateriels = [];
		//请求所有原材料及半成品分类
   			$scope.getAllMaterielClassification = function(){
   				$scope.getJson($scope.resultPath+'/wisdomeatery/v1/canteens/'+$scope.canteenId+'/materialCategories','','get',function(data){
   					console.log(data);
					$scope.materielsFenLei = data.data;
					console.log($scope.materielsFenLei);
				})
   			}
   			
   			//请求所有原材料及半成品
   			$scope.getAllMaterielGoods= function(){
   				console.log($scope.canteenId);
   				console.log($scope.resultPath);
   				$scope.getJson($scope.resultPath+'/wisdomeatery/v1/canteens/'+$scope.canteenId+'/processing_materials_total','','get',function(data){
	   				console.log(data);
	   				$scope.sonsMateriels = data.data;
	   				$scope.smallCategorys = data.data;
	   				$scope.intialSmallCategorys = data.data;
	   			})
   			}
		//获取所有厨师
		$scope.getChiefs = function(){
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/chief",'',"GET",function(data){
						console.log(data);
			 			if( data.code == 0){
			 					$scope.chiefs = data.data;
			 					$scope.chiefId = $scope.chiefs[0].id;
			 					$scope.chief = $scope.chiefs[0].name;
			 			}else{
			 				console.log(data.msg);
			 			}
			 		});
		}
		//查询菜品详细信息
		$scope.searchOneDish = function(){
			//如果dishId 为 add 则是菜品增加 ，不是则为菜品修改
		if( $scope.dishId != 'add'){
			console.log($scope.canteenId);
			console.log($scope.dishId);
			//获取菜品详细信息
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/items/"+$scope.dishId,'',"GET",function(data){
				console.log(data);
			 			if( data.code == 0){
			 					$scope.barCode = data.data[0].barCode ;//菜品条码
			 					$scope.category_id = data.data[0].category_id ;//菜品类别
			 					$scope.shortName = data.data[0].assistCode ;//菜品助记码
			 					$scope.name = data.data[0].name ;
			 					$scope.unitId = data.data[0].unitId ;//菜品单位
			 					$scope.range = '不限' ;//售卖范围
			 					$scope.window = data.data[0].window_id ;//制作档口
			 					$scope.chiefId = data.data[0].chiefId;//厨师id
			 					$scope.chief = data.data[0].chief ;//制作厨师
			 					$scope.kanbanUnitId = data.data[0].manufacturing_unit_id ;//看板出品单位
			 					$scope.unit_converter_ratio = data.data[0].unit_converter_ratio;
			 					$scope.description = data.data[0].description ;//描述
//			 					$scope.weight = data.data[0].weight ;//称重
								$scope.quickDish = data.data[0].isShortCut//是否为快捷菜品
								if( data.data[0].workshop_id != null){
									$scope.workshop_id = data.data[0].workshop_id;//制作档口
								}
								if( data.data[0].procedure_id != null){
									$scope.procedure_id = data.data[0].procedure_id;//制作工序
								}
								if( data.data[0].work_time != null){
									$scope.workTime = data.data[0].work_time;//制作时间
								}
								
								$scope.energy =  data.data[0].energy ;		//能量										
								$scope.protein =  data.data[0].protein ;	//蛋白质					           			
								$scope.fat =  data.data[0].fat ;			//脂肪				           			
								$scope.carbohydrate =  data.data[0].carbohydrate ;	//碳水化合物							        
			 					$scope.maDatas = data.data[0].materials ; //原料
			 					$scope.material_fee = parseFloat(data.data[0].material_fee);//原料成本
			 					$scope.other_chengben = parseFloat(data.data[0].others_fee) ;  //其他成本
			 					$scope.manage_fee = parseFloat(data.data[0].manage_fee) ;  //管理费用
			 					$scope.energe_fee = parseFloat(data.data[0].energe_fee) ;  //能源费
//			 					$scope.others_fee = parseFloat(data.data[0].others_fee) ;  //其他费用
			 					$scope.total_cost = parseFloat(data.data[0].total_cost) ;//总成本
			 					$scope.price = parseFloat(data.data[0].price) ;//价格
			 					$scope.profit = parseFloat(data.data[0].gross_profit) ;//默认毛利率
			 					$scope.sale_rate = parseFloat(data.data[0].sale_rate)   ; //销售系数
			 					var arrpro = data.data[0].properties;
			 					$scope.colors = [];
			 					$scope.tastes = [];
			 					$scope.shapes = [];
			 					for( var i =0;i<arrpro.length ;i++){
			 						if(arrpro[i].gcode == 3041 && arrpro[i].checked == true){//制作方法
			 								$scope.methodId = arrpro[i].id;
			 						}
			 						if(arrpro[i].gcode == 3042){//颜色
			 								$scope.colors.push(arrpro[i]);
			 						}
			 						if(arrpro[i].gcode == 3043){//口味
			 								$scope.tastes.push(arrpro[i]);
			 						}
			 						if(arrpro[i].gcode == 3044){//形状
			 								$scope.shapes.push(arrpro[i]);
			 						}
			 					}
			 					
			 					
			 			}else{
			 				console.log(data.msg);
			 			}
			 		});
		}
		}
		
		
		if( $scope.getCanteenId() != ''){
   				$scope.canteenId =  $scope.getCanteenId() ;
   				//获取某食堂下所有分类
		 		$scope.getCategorys();
		 		//获取所有厨师
		 		$scope.getChiefs();
		 		//获取所有档口
		 		$scope.getWindows();
		 		//获取所有单位
		 		$scope.getUnits();
		 		$scope.getAllMaterielClassification();
   				$scope.getAllMaterielGoods();
   				$scope.getWorkShops();
   				$scope.getProcedures();
   				$timeout(function(){
									$scope.searchOneDish();
								},300);
   				
   			}
		$scope.$on('to-child', function(event,data) {
						 //获取从父控制器传来的当前选中食堂
						$scope.canteenId = data;
						//获取某食堂下所有分类
				 		$scope.getCategorys();
				 		//获取所有厨师
		 				$scope.getChiefs();
		 				//获取所有档口
		 				$scope.getWindows();
		 				//获取所有单位
		 				$scope.getUnits();
		 				$scope.getAllMaterielClassification();
   						$scope.getAllMaterielGoods();
   						$scope.getWorkShops();
   						$scope.getProcedures();
   						$timeout(function(){
									$scope.searchOneDish();
								},300);
				});
		//默认不是记重单位
		$scope.isWeight = false;
		$scope.is_sale_by_weight = 0;
		$scope.unitId = '';
		//打开菜品维护模板
   		$scope.openUnitModal = function(){
   			$("#unitWeihu").modal('toggle')
   		}
   		//关闭菜品维护模板
   		$scope.unit_true = function(){
			$("#unitWeihu").modal('toggle')
		}
		//唤醒新增单位模板
		$scope.addUnit = function(){
			$scope.unitName = '';
   			$scope.isWeight = false
			$("#addUnit").modal('toggle')
		}
		//新增单位模板确定键
		$scope.addUnit_true = function(){
			if( $scope.isWeight == true ){
				$scope.is_sale_by_weight = 1 ;
			}else{
				$scope.is_sale_by_weight = 0 ;
			}
			var postData = {
				'name':$scope.unitName,
				'is_sale_by_weight':$scope.is_sale_by_weight
			}
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/canteen/"+$scope.canteenId+"/unit",postData,"POST",function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$("#addUnit").modal('toggle');
			 				$scope.getUnits();
			 			}else{
			 				$scope.showError(data.msg);
			 			}
			 		});
			
		}
		//唤醒修改单位模板
		$scope.unitEdit = function(unitId,unitName,isSaleByWeight){
			$scope.unitId = unitId ;
			$scope.unitName = unitName ;
			if( isSaleByWeight == 1){
				$scope.isWeight = true;
			}else{
				$scope.isWeight = false;
			}
			
			$("#updateUnit").modal('toggle')
		}
		//修改单位模板确定按钮
		$scope.updateUnit_true = function(){
			if( $scope.isWeight == true ){
				$scope.is_sale_by_weight = 1 ;
			}else{
				$scope.is_sale_by_weight = 0 ;
			}
			
			var postData = {
				'name':$scope.unitName,
				'is_sale_by_weight':$scope.is_sale_by_weight
			}
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/canteen/"+$scope.canteenId+"/unit/"+$scope.unitId,postData,"PUT",function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$("#updateUnit").modal('toggle');
			 				$scope.getUnits();
			 			}else{
			 				$scope.showError(data.msg);
			 			}
			 		});
			
		}
		//唤醒是否删除单位模板
		$scope.unitDel = function(unitId,unitName){
			$scope.unitName = unitName ;
			$scope.unitId = unitId ;
			$("#delUnit").modal('toggle')
		}
		//删除模板确定键
		$scope.del_unit = function(){
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/canteen/"+$scope.canteenId+"/unit/"+$scope.unitId,'',"DELETE",function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$("#delUnit").modal('toggle');
			 				$scope.getUnits();
			 			}else{
			 				$scope.showError(data.msg);
			 			}
			 		});
		}
		
		$scope.quickDish = false;
		//取字符串中汉字首字母方法
		$scope.getPingyin = function(dishName){
			//$scope.shortName = makePy(dishName);
			var shortName = makePy(dishName);
			console.log(shortName);
			if( shortName.indexOf(',') != -1){
				$scope.shortName = shortName.substring(0,shortName.indexOf(','));
			}else{
				$scope.shortName = shortName ;
			}
		}
		

   		$scope.description = '';
   		$scope.name = '';
   		$scope.chiefs = [];
   		$scope.barCode = new Date().getTime();//默认的条码
   		$scope.energy = 0;//能量
   		$scope.protein = 0;//蛋白质
   		$scope.fat = 0;//脂肪
   		$scope.carbohydrate = 0;//碳水化合物
   		$scope.profit = 0.5;//默认利润率
   		//售卖范围
   		$scope.ranges = [
   						{id:'01',name:'不限'},
   						{id:'02',name:'仅就餐终端'},
   						{id:'03',name:'仅预定'},	
   						]
   		$scope.range = '不限';
   		$scope.choiceChief = function(event){
   			 event.stopPropagation();
        	   $("#selectChief").modal('toggle')
   		}
   		 //选中某行后获取该行信息
			$scope.chiefSelected = function(event,id,name){
	    		event.stopPropagation();
	    		//将数据展示区域的所有td背景颜色先去掉
	    		var allTd = document.getElementById('chiefSelected').getElementsByTagName('td');
	    		for(var i = 0;i< allTd.length ; i++ ){
	    			allTd[i].className = '';
	    		}
	    		//保证js点击锁定的是tr标签
	    		var target = event.target ;
	    		if( target.nodeName == 'TD'){
	    			target = target.parentNode ;
	    		}
	    		var p = target.children ;
	    		for(var i = 0;i< p.length ; i++ ){
	    			p[i].className = 'selected';
	    		}
	    		$scope.operatorOrderId = id;//厨师id
	    		$scope.operatorOrderName = name;//厨师姓名
    	}
   		//确定选择某厨师
			$scope.trueSelectChief = function(){
				console.log($scope.operatorOrderName);
				if( $scope.operatorUserName == ''){
					$('#contentHtml').html('请选择厨师');
					$('#warningChoose').modal('toggle');
					return;
				}
				//$('#operatorText').text($scope.operatorUserName);
				$scope.chiefId = $scope.operatorOrderId ;
				$scope.chief = $scope.operatorOrderName ;
				 //显示、隐藏窗口
        	   $("#selectChief").modal('toggle')
			}

		$scope.smallCategorys = [];
		$scope.intialSmallCategorys =[];
        //根据点选的分类名称，获取该分类下有的原料数据
        $scope.getMaterials = function(id){
			console.log(id);
        	var arr = $scope.sonsMateriels ;
        	console.log(arr);
        	var newArr = [];
        	for (var i = 0; i< arr.length ; i++ ) {
        		if( arr[i].categoryId == id || arr[i].category_id == id){
        			newArr.push(arr[i]);
        		}
        	}
        	console.log(newArr);
        	$scope.smallCategorys = newArr ;
        	$scope.intialSmallCategorys = newArr;
        }
        //点击全部分类，获取所有原料及半成品
        $scope.getAll = function(){
        	$scope.smallCategorys = $scope.sonsMateriels ;
        	$scope.intialSmallCategorys = $scope.sonsMateriels;
        }
        //进入页面查询原料分类数据后，先默认展示第1种分类中的数据
          //$scope.getMaterials($scope.materielsFenLei[0].name);
        //物料查询初始值默认为 ‘’
        $scope.goods = '';
        //点击原料分类取值方法
        $scope.sMaterial = function(id){
        	//event.stopPropagation();
        	//var target = event.target ;
        	$scope.getMaterials(id);
        }
        //实时监控物料查询搜索框的值
            $scope.$watch('cardInfor',  function() {
            	if($scope.cardInfor ==undefined){
            		$scope.cardInfor = '';
            	}
		           //准备一个空的数组
		           var newList = [];
		           var arr = $scope.intialSmallCategorys ;
		           console.log(arr);
		           var length = arr.length;
		           	for(var i=0;i<length;i++){
						if(  arr[i].name.indexOf($scope.cardInfor) >= 0 ){
							newList.push(arr[i]);
						}
		           }
		          $scope.smallCategorys =  	newList ;
            });
        //原料标准模板中删除此行
        $scope.delThis = function(event,material_name){
        	event.stopPropagation();
        	var target = event.target;
        	var arr = $scope.maDatas.concat() ;
//      	$(target).parent().parent().remove();
			 for(var i=0; i<arr.length; i++) {
			    if(arr[i].name == material_name) {
			      arr.splice(i, 1);
			      break;
			    }
			  }
			 $scope.maDatas = arr.concat() ;
        }
        $scope.is_major = 1;//主辅料标识，默认为主料
        //点击主料、辅料切换模板
        $scope.clickMainFu = function(val){
        	$scope.is_major = val;
        	if( val == 1){
        		$('#zhu').addClass('aattvv');
        		$('#fu').removeClass('aattvv');
        	}else{
        		$('#fu').addClass('aattvv');
        		$('#zhu').removeClass('aattvv');
        	}
        	
        }
        
        $scope.maDatas = []
        //点击物料行添加物料进标准成分模板中
        $scope.cmaterial = function(event,material_id,material_name,unit,material_cost){
        	event.stopPropagation();
        	var standards = document.getElementsByClassName('maDataList_name');
        	var intial = '0';//默认标准成分模板中没有
        	for(var i = 0; i< standards.length ; i++){
        		if(standards[i].innerHTML == material_name){
        			intial = '1'; //如果模板中已经有这个成分了 就置为1
        		}
        	}
        	if( intial == '0'){//说明模板中没有，需要添加material_id
        		this.maDatas.push( { "id": material_id,"name": material_name, "unit":unit,"num":1 ,"is_major":$scope.is_major});
			}
        	console.log(this.maDatas);
        }
 		
		//模态框出现后调用方法
		var temparr = []
		$('#selectMaterial').on('shown.bs.modal', function (e) {
			temparr = $scope.maDatas.concat()
		})
		//点击取消
		$scope.cancle_edit = function(){
			this.maDatas = temparr
			$('#selectMaterial').modal('toggle')
		}
        //计算原料成本
        $scope.material_fee = 0;//原料费
        $scope.manage_fee = 0;//管理费
        $scope.other_chengben = 0;//其他成本
        $scope.energe_fee = 0;//能源费
        $scope.others_fee = 0;//其他费用
        $scope.price = 0;//价格
        $scope.sale_rate = 0.9;
        $scope.total_cost = parseFloat($scope.manage_fee) + parseFloat($scope.material_fee) + parseFloat($scope.energe_fee) + parseFloat($scope.others_fee) ;
//     	$scope.price = $scope.total_cost*( 1+ $scope.profit) ;
		$scope.price = $scope.total_cost/( 1 - $scope.profit) ;
       //点击原料模板确定键
        $scope.material_true = function(){
        	var arr = $scope.maDatas ;
			var currentCost = 0;
			for( var i=0;i<arr.length;i++){
//				if(  !isNumber(arr[i].num+'')  ){
//					$scope.showError('用料数量必须为正整数');
//					return;
//				}
				if( arr[i].num <=0 ){
					$scope.showError('用料数量必须大于0');
					return;
				}
//				currentCost = currentCost + (parseFloat(arr[i].num) * parseFloat(arr[i].material_cost) );
//				currentCost = 5;
			}
//			$scope.material_fee = currentCost ;//原料成本
//			$scope.total_cost = parseFloat($scope.manage_fee) + parseFloat($scope.material_fee) + parseFloat($scope.energe_fee) + parseFloat($scope.others_fee) ;
			//$scope.price = $scope.total_cost*( 1+ $scope.profit) ;
//			$scope.price = $scope.total_cost/( 1 - $scope.profit) ;
//			console.log($scope.material_fee);
			
			var postData = 
        	{
        		"materials":	$scope.maDatas,//原材料$scope.maDatas
        	}
        	
        	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/canteens/"+$scope.canteenId+"/calcPrice",postData,"POST",function(data){
        				console.log(data);
	           			if(data.code == 0){
	           				$scope.material_fee = data.data ;
	           				$scope.getCostAndProfit();
//	           				var tempVal1 =  parseFloat($scope.material_fee) + parseFloat($scope.manage_fee) + parseFloat($scope.energe_fee) + parseFloat($scope.others_fee) 
//							$scope.total_cost = parseFloat( tempVal1.toFixed(2) );
//							var tempVal2 = $scope.total_cost/(  1 - $scope.profit) ;
//							$scope.price = parseFloat( tempVal2.toFixed(2) );
//							if( checkDouble($scope.price) && ($scope.price + '')!= '' && ($scope.pricee + '')!= 'null' && ($scope.price + '')!= null){
//								$scope.showError('价格只能为小数位数最长2位的正数');
//								$scope.price = 1;
//							}
//							if( $scope.price >= 1000 ){
//								$scope.showError('原料选择过多，请将成本控制在1000以内');
//								$scope.maDatas = [];
//								$scope.material_fee = 0;
//								$scope.total_cost = 0;
//								$scope.profit = 0.5;
//								$scope.price = 0;
//							}
//							if( $scope.price ==undefined || $scope.price == null){
//								$scope.price = 1;
//							}
	           				$("#selectMaterial").modal('toggle')
	           			}else{
	           				$scope.showError(data.msg);
	           			}
	           		});
        	
        }
        $scope.unit_converter_ratio = 1 ;
        //点击原料模板取消键
        $scope.material_cancel = function(event){
        	event.stopPropagation();
        	 $scope.maDatas = zhongjian ;
        	$("#selectMaterial").modal('toggle');
        }
       	//改变原料成本及其他成本及价格时调用此方法
       	$scope.getCostAndProfit = function(){
       		console.log($scope.material_fee);
       		console.log($scope.other_chengben);
       		$scope.total_cost = parseFloat( ($scope.material_fee + $scope.other_chengben).toFixed(2)) ;//总成本
       		console.log($scope.total_cost);
       		$scope.profit =  parseFloat( ( ($scope.price - $scope.total_cost )/$scope.price ).toFixed(2) );  
       		console.log($scope.profit);
       	}
        	
       
        //费用改变时调用此方法
//			$scope.valChange = function(){
//				event.stopPropagation();
//				if( $scope.profit >= 1 ){
//					$scope.showError('毛利率不能大于1');
//					$scope.profit = 0;
//					$scope.price = $scope.material_fee ;
//				}
//				if( $scope.profit <  0 ){
//					$scope.showError('毛利率不能小于0');
//					$scope.profit = 0;
//					$scope.price = $scope.material_fee ;
//				}
//				if( checkDouble( $scope.profit )  ){
//					$scope.showError('毛利率最多可以有两位小数');
//					$scope.profit = 0.5;
//				}
//				if( checkDouble($scope.manage_fee) && ($scope.manage_fee + '')!= '' && ($scope.manage_fee + '')!= 'null' && ($scope.manage_fee + '')!= null){
//					$scope.showError('只能输入小数位数最长2位的正数');
//					$scope.manage_fee = 0;
//				}
//				if( $scope.manage_fee >= 1000 ){
//					$scope.showError('只能输入小于1000的数');
//					$scope.manage_fee = 0;
//				}
//				if( $scope.manage_fee ==undefined || $scope.manage_fee == null){
//					$scope.manage_fee = 0;
//				}
//				if( checkDouble($scope.energe_fee) && ($scope.energe_fee + '')!= '' && ($scope.energe_fee + '')!= 'null' && ($scope.energe_fee + '')!= null){
//					$scope.showError('只能输入小数位数最长2位的正数');
//					$scope.energe_fee = 0;
//				}
//				if( $scope.energe_fee >= 1000 ){
//					$scope.showError('只能输入小于1000的数');
//					$scope.energe_fee = 0;
//				}
//				if( $scope.energe_fee ==undefined || $scope.energe_fee == null){
//					$scope.energe_fee = 0;
//				}
//				if( checkDouble($scope.others_fee) && ($scope.others_fee + '')!= '' && ($scope.others_fee + '')!= 'null' && ($scope.others_fee + '')!= null){
//					$scope.showError('只能输入小数位数最长2位的正数');
//					$scope.others_fee = 0;
//				}
//				if( $scope.others_fee >= 1000 ){
//					$scope.showError('只能输入小于1000的数');
//					$scope.others_fee = 0;
//				}
//				if( $scope.others_fee ==undefined || $scope.others_fee == null){
//					$scope.others_fee = 0;
//				}
//				var manage_fee = $scope.manage_fee ;
//				var material_fee = $scope.material_fee ;
//				var energe_fee = $scope.energe_fee ;
//				var others_fee = $scope.others_fee ;
//				if($scope.manage_fee == '' || $scope.manage_fee == undefined){
//					manage_fee = 0;
//				}
//				if($scope.material_fee == '' || $scope.material_fee == undefined){
//					material_fee = 0;
//				}
//				if($scope.energe_fee == '' || $scope.energe_fee == undefined){
//					energe_fee = 0;
//				}
//				if($scope.others_fee == '' || $scope.others_fee == undefined){
//					others_fee = 0;
//				}
//				var tempVal1 =  parseFloat(manage_fee) + parseFloat(material_fee) + parseFloat(energe_fee) + parseFloat(others_fee) 
//				$scope.total_cost = parseFloat( tempVal1.toFixed(2) );
////				var tempVal2 = $scope.total_cost*( 1+ $scope.profit) ;
//				var tempVal2 = $scope.total_cost/(  1 - $scope.profit) ;
//				$scope.price = parseFloat( tempVal2.toFixed(2) );
//				if( checkDouble($scope.price) && ($scope.price + '')!= '' && ($scope.pricee + '')!= 'null' && ($scope.price + '')!= null){
//					$scope.showError('价格只能为小数位数最长2位的正数');
//					$scope.price = 0;
//				}
//				if( $scope.price >= 1000 ){
//					$scope.showError('价格需小于1000');
//					$scope.price = 0;
//					$scope.total_cost = 0;
//					$scope.manage_fee = 0;
//					$scope.energe_fee = 0;
//					$scope.others_fee = 0;
//					$scope.profit = 0.5;
//				}
//				if( $scope.price ==undefined || $scope.price == null){
//					$scope.price = 0;
//				}
//			}
			//销售系数说明
			$scope.explain = function(){
				$('#contentHtml').html('1、菜品销售系数可理解为该菜品每餐每人消费份数，对菜品销售预测及制定生产计划起指导作用。2、如：某菜品销售系数设置0.4，消费人数为1000人，则该菜品某餐别预计销售数量为400份。');
				$('#warningChoose').modal('toggle');
			}
			//默认毛利率说明
			$scope.explain2 = function(){
				$('#contentHtml').html('毛利率=毛利/价格×100%=（价格-总成本）/价格×100%');
				$('#warningChoose').modal('toggle');
			}
			var workTimecount = 0;
			//制作时间改变
			$scope.workTimeChange = function(){
				if( !isNumber($scope.workTime) ){
					$scope.workTime = $scope.workTime.substring(0,workTimecount);
				}
				workTimecount = $scope.workTime.length;
			}
			//
			$scope.UnitName = '';
			$scope.bianhua = function(){
				console.log($scope.unitId);
				var unitarr = $scope.units.concat();
				for(var i = 0; i< unitarr.length ; i++){
					if(unitarr[i].id == $scope.unitId){
						$scope.UnitName = unitarr[i].name ;
						unitarr.splice(i,1);
					}
				}
				$scope.kanbanUnits = unitarr.concat();
				$scope.kanbanUnitId = $scope.kanbanUnits[0].id;
			}
			var barCodecount = 0;
			//条码改变
			$scope.barCodeChange = function(){
				if( !isNumber($scope.barCode) ){
					$scope.barCode = $scope.barCode.substring(0,barCodecount);
				}
				barCodecount = $scope.barCode.length;
			}
			
           	//菜品信息保存
           	$scope.dishInforSave = function(){
           		
           			var categorys = $scope.categorys ;
	           		for(var i =0; i< categorys.length ;i++){
	           			if(categorys[i].id == $scope.category_id){
	           				$scope.category_name = categorys[i].name ;
	           			}
	           		}
	           		var totalPercent = $scope.energy + $scope.protein + $scope.fat + $scope.carbohydrate ;
	           		var postdd = [];
	           		var arrm = $scope.methods ;
	           		var arrt = $scope.tastes ;
	           		var arrc = $scope.colors ;
	           		var arrshape = $scope.shapes ;
	           		
	           		for( var i = 0; i<arrm.length;i++){
	           			if(arrm[i].id == $scope.methodId){
	           				postdd.push(arrm[i]);
	           			}
	           		}
	           		for( var i = 0; i<arrt.length;i++){
	           			if(arrt[i].checked ){
	           				postdd.push(arrt[i]);
	           			}
	           		}
	           		for( var i = 0; i<arrc.length;i++){
	           			if(arrc[i].checked ){
	           				postdd.push(arrc[i]);
	           			}
	           		}
	           		for( var i = 0; i<arrshape.length;i++){
	           			if(arrshape[i].checked ){
	           				postdd.push(arrshape[i]);
	           			}
	           		}
	           		//保存校验
	           		if( isNull($scope.barCode) == true){
	           			$scope.showError('条码不能为空');
	           			return;
	           		}
	           		if(  !isNumber($scope.barCode+'') ){
	           			$scope.showError('条码必须为正整数');
	           			return;
	           		}
	           		if( $scope.barCode.length > 20){
	           			$scope.showError('条码长度过长');
	           			return;
	           		}
	           		if( isNull($scope.workTime) == true){
	           			$scope.showError('制作时间不能为空');
	           			return;
	           		}
	           		if(  parseInt($scope.workTime) < 0 ){
	           			$scope.showError('制作时间必须大于0');
	           			return;
	           		}
	           		if(  parseInt($scope.workTime) >= 10000 ){
	           			$scope.showError('制作时间不得大于10000');
	           			return;
	           		}
	           		if(  $scope.barCode.length > 20){
	           			$scope.showError('条码位数大得大于20');
	           			return;
	           		}
	           		if( isNull($scope.name) == true){
	           			$scope.showError('菜品名称不能为空');
	           			return;
	           		}
	           		if( $scope.name.length > 20){
	           			$scope.showError('菜品名称长度不得大于20位');
	           			return;
	           		}
	           		if( isNull($scope.shortName) == true){
	           			$scope.showError('助记码不能为空');
	           			return;
	           		}
	           		if( $scope.shortName.length > 20){
	           			$scope.showError('助记码长度不得大于20位');
	           			return;
	           		}
//	           		if( isNull($scope.processTime) == true){
//	           			$scope.showError('加工时长不能为空');
//	           			return;
//	           		}
//					console.log($scope.window);
//					console.log($scope.workshop_id);
//	           		console.log($scope.procedure_id);
	           		if( $scope.window == undefined || $scope.window == null){
	           			$scope.showError('请先添加售卖档口，再创建菜品');
	           			return;
	           		}
	           		if( $scope.workshop_id == undefined || $scope.workshop_id == null){
	           			$scope.showError('请先添加制作车间，再创建菜品');
	           			return;
	           		}
	           		if( $scope.procedure_id == undefined || $scope.procedure_id == null){
	           			$scope.showError('请先添加制作工序，再创建菜品');
	           			return;
	           		}
//	           		if( isNull($scope.chiefId) == true){
//	           			$scope.showError('请选择厨师');
//	           			return;
//	           		}
//	           		if( $scope.description.length > 100){
//	           			$scope.showError('菜品简介长度不得大于100');
//	           			return;
//	           		}
	           		if( totalPercent > 100){
	           			$scope.showError('营养成分之和不能大于100%');
	           			return;
	           		}
	           		if( $scope.energy<0 || $scope.energy > 100 || $scope.protein<0 || $scope.protein > 100|| $scope.fat<0 || $scope.fat > 100|| $scope.carbohydrate<0 || $scope.carbohydrate > 100){
	           			$scope.showError('每种营养成分的值必须在0-100之间');
	           			return;
	           		}
//	           		if( $scope.maDatas.length == 0){
//	           			$scope.showError('请选择原料标准成分');
//	           			return;
//	           		}
	           		if( isNull($scope.price+'') == true){
	           			$scope.showError('价格不能为空');
	           			return;
	           		}
//	           		if( isNull($scope.material_fee+'') == true){
//	           			$scope.showError('原料成本不宜为空');
//	           			return;
//	           		}
//	           		if( $scope.material_fee <= 0 ){
//	           			$scope.showError('原料成本必须大于0');
//	           			return;
//	           		}
//	           		if( $scope.material_fee >= 1000 ){
//	           			$scope.showError('原料成本不得大于1000');
//	           			return;
//	           		}
//	           		if( $scope.manage_fee >= 1000 ){
//	           			$scope.showError('管理费必须小于1000');
//	           			return;
//	           		}
//	           		if( $scope.energe_fee >= 1000 ){
//	           			$scope.showError('能源费必须小于1000');
//	           			return;
//	           		}
//	           		if( $scope.others_fee >= 1000 ){
//	           			$scope.showError('其他费用必须小于1000');
//	           			return;
//	           		}
//	           		if( $scope.total_cost >= 1000 ){
//	           			$scope.showError('总成本必须小于1000');
//	           			return;
//	           		}
//	           		if( $scope.total_cost <= 0 ){
//	           			$scope.showError('总成本必须大于0');
//	           			return;
//	           		}
//	           		if( $scope.price >= 1000 ){
//	           			$scope.showError('价格必须小于1000');
//	           			return;
//	           		}
	           		if( $scope.price <= 0 ){
	           			$scope.showError('价格必须大于0');
	           			return;
	           		}
//	           		if( $scope.total_cost > $scope.price ){
//	           			$scope.showError('价格需比总成本高');
//	           			return;
//	           		}
	           		if( isNaN($scope.price)  ){
	           			$scope.showError('价格不能为空');
	           			return;
	           		}
	           		if( checkDouble( $scope.price )  ){
						$scope.showError('价格最多可以有两位小数');
						$scope.profit = 0.5;
						return;
					}
//	           		if( isNull($scope.profit+'') == true || $scope.profit == null){
//	           			$scope.showError('请填写毛利率');
//	           			return;
//	           		}
//	           		if( $scope.profit >= 1 || $scope.profit<= 0){
//	           			$scope.showError('毛利率必须在0-1之间');
//	           			return;
//	           		}
//	           		if( isNull($scope.sale_rate+'') == true){
//	           			$scope.showError('请填写销售系数');
//	           			return;
//	           		}
//	           		if( $scope.sale_rate > 1 || $scope.sale_rate < 0){
//	           			$scope.showError('销售系数必须在0-1之间');
//	           			return;
//	           		}
	           		
	           		var postData = {
           				"barCode":$scope.barCode+'',//条码	
           				"category_id":$scope.category_id,//菜品类别ID
	           			"name":	$scope.name,//菜品名
	           			"shortName":	$scope.shortName,//菜品名助记码
	           			"unit":	$scope.unitId,//单位
	           			"window_id":	$scope.window,//所属档口id
	           			"chief":	$scope.chiefId,//厨师
	           			"gcodes":	postdd,
	           			"isQuick":	$scope.quickDish,//是否为快捷菜品
	           			"description":	$scope.description,//描述
	           			"energy":	$scope.energy,//能量
	           			"protein":	$scope.protein,//蛋白质
	           			"fat":	$scope.fat,//脂肪
	           			"carbohydrate":	$scope.carbohydrate,//碳水化合物
	           			"materials":	$scope.maDatas,//原材料$scope.maDatas
	           			"material_fee":	$scope.material_fee,//原料成本
	           			"others_fee":	$scope.other_chengben,//其他成本
//	           			"cost_other":	$scope.other_chengben,//其他成本
	           			"total_cost":	$scope.total_cost,//总成本
	           			"price":	$scope.price,//外部价格
	           			"manage_fee":	$scope.manage_fee,//管理费
	           			"energe_fee":	$scope.energe_fee,//能源费
	           			"gross_profit":	 $scope.profit + '',//毛利率
	           			"sale_rate":	 $scope.sale_rate + '',//销售系数
	           			"workshop_id":	 $scope.workshop_id,//制作档口id
	           			"work_time":	 $scope.workTime,//制作时间
	           			'procedure_id':  $scope.procedure_id,//制作工序
	           			"unit_converter_ratio":	 $scope.unit_converter_ratio,//转换系数
	           			'manufacturing_unit_id':  $scope.kanbanUnitId,//生产看板单位id
	           		}
	           		console.log(postData);
           		if( $scope.dishId == 'add'){//说明是新增
           				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/items",postData,"POST",function(data){
	           			console.log(data);
	           			if(data.code == 0){
	           				$scope.showSuccess('操作成功！');
	           				$scope.jump_back();
	           			}else{
	           				$scope.showError(data.msg);
	           			}
	           		});
           		}else{//修改
           			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/items/"+$scope.dishId,{
           				"barCode":$scope.barCode+'',//条码	
	           			"name":	$scope.name,//菜品名
	           			"shortName":	$scope.shortName,//菜品名助记码
	           			"category_id":$scope.category_id,//菜品类别ID
	           			"window_id":	$scope.window,//所属档口id
	           			"chief":	$scope.chiefId,//厨师
	           			"unitId":	$scope.unitId,//单位
	           			"properties":	postdd,//制作方法，口味，颜色
	           			"isQuick":	$scope.quickDish,//是否为快捷菜品
	           			"description":	$scope.description,//描述
	           			"energy":	$scope.energy,//能量
	           			"protein":	$scope.protein,//蛋白质
	           			"fat":	$scope.fat,//脂肪
	           			"carbohydrate":	$scope.carbohydrate,//碳水化合物
	           			"materials":	$scope.maDatas,//原材料$scope.maDatas
	           			"material_fee":	$scope.material_fee,//原料成本
	           			"others_fee":	$scope.other_chengben,//其他成本
//	           			"cost_other":	$scope.other_chengben,//其他成本
	           			"total_cost":	$scope.total_cost,//总成本
	           			"price":	$scope.price,//外部价格
	           			"manage_fee":	$scope.manage_fee,//管理费
	           			"energe_fee":	$scope.energe_fee,//能源费
//	           			"others_fee":	$scope.others_fee,//其他费用
	           			"gross_profit":	 $scope.profit + '',//毛利率
	           			"sale_rate":	 $scope.sale_rate,//销售系数
	           			"workshop_id":	 $scope.workshop_id,//制作档口id
	           			"work_time":	 $scope.workTime,//制作时间
	           			'procedure_id':  $scope.procedure_id,//制作工序
	           			"unit_converter_ratio":	 $scope.unit_converter_ratio,//转换系数
	           			'manufacturing_unit_id':  $scope.kanbanUnitId,//生产看板单位id
	           		},"PUT",function(data){
	           			console.log(data);
	           			if(data.code == 0){
	           				$scope.showSuccess('操作成功！');
	           				$scope.jump_back();
	           			}else{
	           				$scope.showError(data.msg);
	           			}
	           		});
           		}
           	}
    }])
	//菜谱模板
   .controller('menuTemplateCtrl', ['$scope', '$timeout', function ($scope, $timeout) {
   	$(".modal-dialog").draggable();//为模态对话框添加拖拽
        $(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动
   		//某食堂下所有模板
   		$scope.getTemplates = function(){
   			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templates",'',"GET",function(data){
			 			if( data.code == 0){
			 					$scope.templates = data.data;
			 					if( data.data.length != 0){
			 						$scope.templeId = $scope.templates[0].id;
									$scope.templeName = $scope.templates[0].name;
									//查询第1个模板对应的菜品
									$scope.searchDishes($scope.templates[0].id,$scope.templates[0].name);
			 					}
			 			}else{
			 				console.log(data.msg);
			 			}
			 		});
   		}
   			if( $scope.getCanteenId() != ''){
   				$scope.canteenId =  $scope.getCanteenId() ;
   				//获取某食堂下所有模板
		 		$scope.getTemplates();
   			}
		   	$scope.$on('to-child', function(event,data) {
						 //获取从父控制器传来的当前选中食堂
						$scope.canteenId = data;
						//获取某食堂下所有模板
		 				$scope.getTemplates();
				});
   		$scope.intialInfors = [] ;
   		//点击模板查询对应的菜品
   		$scope.searchDishes = function(id,name){
   			$('.menuTemple').each(function(){
	   				$(this).removeClass('selected');
	   			});
			$('#menuTemple_'+id).addClass('selected');
   			
   			$scope.templeId = id;
			$scope.templeName = name;
   			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templates/"+id+"/items",'',"GET",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.dishesInfors = data.data;
			 				$scope.intialInfors = data.data;
			 			}else{
			 				console.log(data.msg);
			 			}
		 		});
   		}
   		 //实时监控搜索框的值
            $scope.$watch('cardInfor',  function() {
            	if($scope.cardInfor ==undefined){
            		$scope.cardInfor = '';
            	}
		           //准备一个空的数组
		           var newList = [];
		           var arr = $scope.intialInfors ;
		           var length = arr.length;
		           	for(var i=0;i<length;i++){
						if(  arr[i].name.indexOf($scope.cardInfor) >= 0	){
							newList.push(arr[i]);
						}
		           }
		           $scope.dishesInfors = newList;
            });
            //删除某个菜品
            $scope.dish_del = function(id,name){
            	$scope.dish_name = name;
            	$scope.dish_id = id;
            	$('#cancelDish').modal('toggle');
            }
            //删除菜品
            $scope.del_dish = function(){
            	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templates/"+$scope.templeId+"/items/"+$scope.dish_id,'',"DELETE",
          				function(data){
				 			if( data.code == 0){
				 				$scope.searchDishes($scope.templeId,$scope.templeName);
				 				$('#cancelDish').modal('toggle');
				 			}else{
				 				console.log(data.msg);
				 			}
				 		});
            }
            $scope.addTemple = function(){
            	$scope.templeName_add = undefined;
            	$("#addTemple").modal('toggle');
            }
            //新增模板的确定按钮
            $scope.addTemple_true = function(){
            	if($scope.templeName_add == undefined || $scope.templeName_add == ''){
            		$scope.templeName_add = '';
            		return;
            	}
            	var postData = {"name": $scope.templeName_add}
            	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templates",postData,"POST",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				//获取某食堂下所有模板
		 					$scope.getTemplates();
			 				$("#addTemple").modal('toggle');
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
            }
            //点击模板修改按钮
            $scope.updateTemple = function(){
            	if( $scope.templeName == undefined){
        			$('#contentHtml').html('请选择模板类别');
					$('#warningChoose').modal('toggle');
					return;
            	}
            	$("#updateTemple").modal('toggle')
            }
          	//修改模板的确定按钮
          	$scope.updateTemple_true = function(){
          		if($scope.templeName == undefined || $scope.templeName == ''){
            		$scope.templeName = '';
            		return;
            	}
          		var postData = {"name": $scope.templeName}
            	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templates/"+$scope.templeId,postData,"PUT",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				//获取某食堂下所有模板
		 					$scope.getTemplates();
			 				$("#updateTemple").modal('toggle');
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
          	}
          	//点击模板删除按钮
          	$scope.delTemple = function(){
          		if( $scope.templeId == ''){
        			$('#contentHtml').html('请选择模板');
					$('#warningChoose').modal('toggle');
					return;
            	}
          		$("#delTemple").modal('toggle')
          	}
           	 //删除菜品类别
            $scope.del_temple = function(){
            	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templates/"+$scope.templeId,'',"DELETE",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				//获取某食堂下所有模板
		 					$scope.getTemplates();
			 				$("#delTemple").modal('toggle');
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
            }
   }])
	//模板编辑
   .controller('templateEditCtrl', ['$scope', '$timeout','$routeParams',function ($scope, $timeout,$routeParams) {
   	$(".modal-dialog").draggable();//为模态对话框添加拖拽
        $(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动
   			$scope.tempId = $routeParams.tempId ;
   			$scope.tempName = $routeParams.tempName ;
   			$scope.dishesInfors= [];
   			$scope.choiceDish = [];
   			$scope.intial = [];
   			$scope.currentData = [];
   			//获取食堂下所有分类
   			$scope.getCategorys = function(){
   				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/categorys",'',"GET",function(data){
				 			if( data.code == 0){
				 					$scope.classify = data.data;  
				 			}else{
				 				console.log(data.msg);
				 			}
				 		});
   			}
   			//获取某食堂下所有菜品
   			$scope.getDishes = function(){
   				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/items",'',"GET",function(data){
				 			if( data.code == 0){
				 					$scope.dishesInfors = data.data;  
				 					$scope.intial = $scope.dishesInfors.concat() ;
    								$scope.currentData = $scope.dishesInfors.concat() ;
    								//获取选中菜品信息
		 							$scope.getChoicedDished();
				 			}else{
				 				console.log(data.msg);
				 			}
				 		});
   			}
   			//当前模板被选中的菜品信息
    		$scope.getChoicedDished = function(){
    			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templates/"+$scope.tempId+"/items",'',"GET",
	            	function(data){
			 			if( data.code == 0){
			 					$scope.choiceDish = data.data;
			 					var dishArr = $scope.dishesInfors ;
					    		var choiceArr = $scope.choiceDish ;
					    		for(var i =0; i< dishArr.length ;i++){
					    			dishArr[i].checked = false;
					    			for(var j=0;j< choiceArr.length ;j++){
					    				if(dishArr[i].id == choiceArr[j].id){
					    					dishArr[i].checked = true;
					    					dishArr[i].count = choiceArr[j].count ;
					    				}
					    			}
					    		}
					    		$scope.dishesInfors = dishArr ;
			 			}else{
			 				console.log(data.msg);
			 			}
		 		});
    		}
   			if( $scope.getCanteenId() != ''){
   				$scope.canteenId =  $scope.getCanteenId() ;
   				//获取某食堂下所有分类
		 		$scope.getCategorys();
		 		//获取所有菜品
		 		$scope.getDishes();
		 		//获取选中菜品信息
		 		//$scope.getChoicedDished();
   			}
		   	$scope.$on('to-child', function(event,data) {
						 //获取从父控制器传来的当前选中食堂
						$scope.canteenId = data;
						//获取某食堂下所有分类
				 		$scope.getCategorys();
				 		//获取所有菜品
				 		$scope.getDishes();
				 		//获取选中菜品信息
		 				//$scope.getChoicedDished();
				});
    		$scope.intial = $scope.dishesInfors ;
    		$scope.currentData = $scope.dishesInfors ;
    		 //实时监控搜索框的值
            $scope.$watch('cardInfor',  function() {
            	if($scope.cardInfor ==undefined){
            		$scope.cardInfor = '';
            	}
		           //准备一个空的数组
		           var newList = [];
		           var arr = $scope.currentData ;
		           var length = arr.length;
		           
		           	for(var i=0;i<length;i++){
						if(  arr[i].name.indexOf($scope.cardInfor) >= 0	){
							newList.push(arr[i]);
						}
		           }
		           //$scope.pagination(newList);
		           $scope.dishesInfors = newList;
            });
    		 $scope.categoryId = '';
            $scope.categoryName = '';
            //点击全部类别
            $scope.allCategory = function(){
            	 $scope.dishesInfors =$scope.intial.concat() ;
            	 $scope.currentData = $scope.intial.concat() ;
            	  $scope.categoryId = '';
            	  $scope.categoryName = '';
            }
            //点击菜品类别
            $scope.choiceCategory = function(event,id){
            	event.stopPropagation();
            	var target = event.target ;
            	var category = target.innerHTML ;
            	 //准备一个空的数组
		           var newList = [];
		           var arr = $scope.intial ;
		           var length = arr.length;
		           	for(var i=0;i<length;i++){
						if(  arr[i].category_name == category	){
							newList.push(arr[i]);
						}
		           }
			       $scope.currentData =  newList ;
			       $scope.categoryId = id;
			       $scope.categoryName = category;
		           //$scope.pagination(newList);
		           $scope.dishesInfors = newList;
            }
   		//保存选中的菜品数据
   		$scope.templeSave = function(){
   			var arr = $scope.dishesInfors ;
   			var list = [];
   			for( var i = 0; i<arr.length ; i++){
   				if( arr[i].checked == true){
   					list.push({'id':arr[i].id,'count':arr[i].count,'category_id':arr[i].category_id,'unit_id':arr[i].unit_id});
   					if(arr[i].count == undefined || arr[i].count == '' || arr[i].count == '0'){
   						$scope.showError('供应数量不能为空');
   						return;
   					}
   				}
   			}
   			var postData = {
						"items": list
						}
        	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templates/"+$scope.tempId+"/items",postData,"PUT",
            	function(data){
		 			if( data.code == 0){
		 				$scope.showSuccess('操作成功！');
		 				$scope.jump_back();
		 			}else{
		 				console.log(data.msg);
		 			}
	 		});
   		}
   			
   			//时时判断输入的供应数量
   			$scope.valChange = function(val,index){
   				var arr = $scope.dishesInfors;
   				if( !isNumber(val)  ){
   					$scope.dishesInfors[index].count =  parseInt($scope.dishesInfors[index].count);
   				}
   			}
   		
   		
   		
   }])
	//菜谱发布
   .controller('dishPublishCtrl', ['$scope', '$timeout', function ($scope, $timeout) {
   		$(".modal-dialog").draggable();//为模态对话框添加拖拽
        $(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动
   		$scope.menus = [];
   		$scope.intial= [];
   		
		$scope.corporation='';
		$scope.getJson($scope.resultPath+"/wisdomeatery/v1/base_system/enterprise",'','GET',function(data){
			console.log(data);
			if(data.data != null){
				$scope.corporation = data.data[0].name;
			}
		})
// 	//获取当前时间(年月日)
//      $scope.getNowFormatDate = function() {
//		    var date = new Date();
//		    var seperator1 = "-";
//		    var seperator2 = ":";
//		    var month = date.getMonth() + 1;
//		    var strDate = date.getDate();
////		    console.log(date.getHours());
////		    console.log(date.getHours());
//		    if (month >= 1 && month <= 9) {
//		        month = "0" + month;
//		    }
//		    if (strDate >= 0 && strDate <= 9) {
//		        strDate = "0" + strDate;
//		    }
//		    var now = date.getFullYear() + seperator1 + month + seperator1 + strDate;
//		    return now;
//		}
        //获取两个时间差几天
        $scope.distance_days = function(end_str,sta_str){
        	//结束时间  
			var end_date = new Date(end_str);//将字符串转化为时间  
			//开始时间  
			var sta_date = new Date(sta_str);  
			var num = (end_date-sta_date)/(1000*3600*24);//求出两个时间的时间差，这个是天数  
			var days = parseInt(Math.ceil(num));//转化为整天（小于零的话剧不用转了）  
			return days;
        }
         //获取两个时间之差（精确到秒）
        $scope.distance_seconds = function(end_str,sta_str){
        	//结束时间  
			var end_date = new Date(end_str);//将字符串转化为时间  
			//开始时间  
			var sta_date = new Date(sta_str);  
			var num = (end_date-sta_date);
//			var days = parseInt(Math.ceil(num));//转化为整天（小于零的话剧不用转了）  
			return num;
        }
//      console.log( $scope.distance_days('2017-05-15 ','2017-05-15'));
//		console.log( $scope.distance_seconds('2017-05-15 12:40:50','2017-05-15 12:40:51'));
        //获取与传入日期差几天的日期
        $scope.getDisDate = function(time , range){
        	var timeDate = new Date(time); //传入日期   
        	var wDate = new Date(timeDate.getFullYear(), timeDate.getMonth(), timeDate.getDate() + range );  
    		return  $scope.formatDate(wDate); 
        }
        //格式化日期
        $scope.formatDate =function(date){
        	 var myyear = date.getFullYear();   
		    var mymonth = date.getMonth()+1;   
		    var myweekday = date.getDate();  
		    //alert("formatDate"+myyear+":"+mymonth+":"+myweekday)  
		    if(mymonth < 10){   
		        mymonth = "0" + mymonth;   
		    }   
		    if(myweekday < 10){   
		        myweekday = "0" + myweekday;   
		    }   
		    return (myyear+"-"+mymonth + "-" + myweekday);   
        }
        //获得传入日期那周的周一日期
        $scope.getWeekStartDate = function(time){
        	var timeDate = new Date(time); //传入日期   
        	var weekStartDate = new Date(timeDate.getFullYear(), timeDate.getMonth(), timeDate.getDate() - timeDate.getDay()+1);  
    		return  $scope.formatDate(weekStartDate); 
        }
        //获得传入日期那周的周日日期
        $scope.getWeekEndDate = function(time){
        	var timeDate = new Date(time); //传入日期   
        	var weekendDate = new Date(timeDate.getFullYear(), timeDate.getMonth(), timeDate.getDate() - timeDate.getDay()+7);  
    		return  $scope.formatDate(weekendDate); 
        }
        //点击上一周
        $scope.upperWeek = function(){
        	var temp = $scope.rangeStartDate.concat() ;
        	$scope.rangeStartDate = $scope.getDisDate(temp , -7);
        	$scope.weekOne = $scope.rangeStartDate.substring(5,10);
        	$scope.weekTwo = $scope.getDisDate(temp , -6).substring(5,10);
	        $scope.weekThree = $scope.getDisDate(temp , -5).substring(5,10);
	        $scope.weekFour =$scope.getDisDate(temp , -4).substring(5,10);
	        $scope.weekFive = $scope.getDisDate(temp , -3).substring(5,10);
	        $scope.weekSix =$scope.getDisDate(temp , -2).substring(5,10);
        	$scope.rangeEndDate = $scope.getDisDate(temp , -1);
        	$scope.weekSeven =$scope.rangeEndDate.substring(5,10);
        	$scope.getMenus();
//      	$scope.filterDatas($scope.rangeStartDate,$scope.intial);
        }
        //点击下一周
        $scope.nextWeek = function(){
        	var temp = $scope.rangeStartDate.concat() ;
        	$scope.rangeStartDate = $scope.getDisDate(temp , 7);
        	$scope.weekOne = $scope.rangeStartDate.substring(5,10);
        	$scope.weekTwo = $scope.getDisDate(temp , 8).substring(5,10);
	        $scope.weekThree = $scope.getDisDate(temp , 9).substring(5,10);
	        $scope.weekFour =$scope.getDisDate(temp , 10).substring(5,10);
	        $scope.weekFive = $scope.getDisDate(temp , 11).substring(5,10);
	        $scope.weekSix =$scope.getDisDate(temp , 12).substring(5,10);
        	$scope.rangeEndDate = $scope.getDisDate(temp , 13);
        	$scope.weekSeven =$scope.rangeEndDate.substring(5,10);
        	$scope.getMenus();
//      	$scope.filterDatas($scope.rangeStartDate,$scope.intial);
        }
        //点击今天
        $scope.goToToday = function(){
        	var temp = $scope.getWeekStartDate( $scope.getNowFormatDate() ) ;
        	$scope.rangeStartDate = $scope.getWeekStartDate( $scope.getNowFormatDate() ) ;
        	$scope.weekOne = $scope.rangeStartDate.substring(5,10);
        	$scope.weekTwo = $scope.getDisDate(temp , 8).substring(5,10);
	        $scope.weekThree = $scope.getDisDate(temp , 9).substring(5,10);
	        $scope.weekFour =$scope.getDisDate(temp , 10).substring(5,10);
	        $scope.weekFive = $scope.getDisDate(temp , 11).substring(5,10);
	        $scope.weekSix =$scope.getDisDate(temp , 12).substring(5,10);
        	$scope.rangeEndDate = $scope.getWeekEndDate( $scope.getNowFormatDate() ) ;
        	$scope.weekSeven =$scope.rangeEndDate.substring(5,10);
        	$scope.getMenus();
//      	$scope.filterDatas(temp,$scope.intial);
        }
        //判断计划背景颜色
        $scope.isDate = function(pointed_date){
//      	console.log($scope.distance_days($scope.getNowFormatDate(),pointed_date) > 0 ? true :false);
          	return $scope.distance_days($scope.getNowFormatDate(),pointed_date) > 0 ? true :false ;//计划日期比当前日期小的，背景颜色变为灰色
        }
		//刚进页面确定周初始值2017-05-15&nbsp;&nbsp;&nbsp;&nbsp;至&nbsp;&nbsp;&nbsp;&nbsp;2017-05-21
        $scope.rangeStartDate = $scope.getWeekStartDate( $scope.getNowFormatDate() ) ;
        $scope.weekOne = $scope.rangeStartDate.substring(5,10);
        $scope.weekTwo = $scope.getDisDate($scope.rangeStartDate,1).substring(5,10);
        $scope.weekThree = $scope.getDisDate($scope.rangeStartDate,2).substring(5,10);
        $scope.weekFour =$scope.getDisDate($scope.rangeStartDate,3).substring(5,10);
        $scope.weekFive = $scope.getDisDate($scope.rangeStartDate,4).substring(5,10);
        $scope.weekSix = $scope.getDisDate($scope.rangeStartDate,5).substring(5,10);
        $scope.rangeEndDate = $scope.getWeekEndDate( $scope.getNowFormatDate() ) ;
        $scope.weekSeven = $scope.rangeEndDate.substring(5,10);
        $scope.periods = [];
        $scope.templates = [];
        $scope.maDatas = [];
        $scope.dishesInfors = [];
        $scope.classify =[];
        $scope.classDishes = [];
//      $scope.intialInfors = [];
		//日历选择
		$('#sourceDay').datepicker({
		  autoclose: true
		});
		$('#toStratDay').datepicker({
		  autoclose: true
		});
		$('#toEndDay').datepicker({
		  autoclose: true
		});
		$('#checkDay').datepicker({
		  autoclose: true
		});
		//打开菜谱复制模板
		$scope.planCopy = function(){
			$('#planCopy').modal('toggle');
		}
		$scope.apply_to_saturday = false;
		$scope.apply_to_sunday = false;
		//复制确定按钮
		$scope.copy_true = function(){
			if( isNull( $('#sourceDay').val() ) == true){
           			$scope.showError('源日期不能为空');
           			return;
           		}
			if( isNull( $('#toStratDay').val() ) == true ){
           			$scope.showError('目标起始日期不能为空');
           			return;
           		}
			if( isNull( $('#toEndDay').val() ) == true ){
           			$scope.showError('目标结束日期不能为空');
           			return;
           		}
			if( $scope.distance_days( $('#toEndDay').val(),$('#toStratDay').val() ) < 0 ){
				$scope.showError('目标结束日期不能小于起始日期');
           			return;
			}
			var postData = {
							"source_date": $('#sourceDay').val(),
							"target_start_date": $('#toStratDay').val(),
							"target_end_date": $('#toEndDay').val(),
							"apply_to_saturday": $scope.apply_to_saturday,
							"apply_to_sunday": $scope.apply_to_sunday
						}
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menu_plans/canteens/"+$scope.canteenId+"/copy",postData,"POST",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$scope.getMenus();
			 				$('#planCopy').modal('toggle');
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
		}
        //切换模板查询对应的菜品
   		$scope.searchDishes = function(){
   			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templates/"+$scope.template_id+"/items",'',"GET",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.dishesInfors = data.data;
			 				$scope.maDatas = data.data;
			 				var arr = $scope.dishesInfors ;
//			 				$scope.intialInfors = data.data;
							for(var i = 0; i< arr.length ; i++){
			   					if( i == (arr.length -1) ){
			   						content += arr[i].name ;
			   					}else{
			   						content += arr[i].name +',' ;
			   					}
			   				}
		   					$('#dishText').text(content);
			 			}else{
			 				console.log(data.msg);
			 			}
		 		});
   		}
        //某食堂下所有模板
   		$scope.getTemplates = function(){
   			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templates",'',"GET",function(data){
			 			if( data.code == 0){
			 					$scope.templates = data.data;
			 					if(data.data.length != 0){
			 						$scope.template_id = $scope.templates[0].id;
			 						$scope.template_name = $scope.templates[0].name;
			 					}
			 			}else{
			 				console.log(data.msg);
			 			}
			 		});
   		}
   		//餐别种类数量
   		$scope.periodNum = '';
        //查询某一食堂下所有餐别信息
        $scope.getPeriod_time = function(){
        	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/base_system/canteens/"+$scope.canteenId+"/periodTimes",'',"GET",
        			function(data){
        				console.log(data);
			 			if( data.code == 0){
			 					$scope.periods = data.data;
			 					if( $scope.periods != null){
			 						$scope.periodNum = $scope.periods.length;
			 					}
			 			}else{
			 				console.log(data.msg);
			 			}
			 		});
        }
       
         //所有菜谱信息
        $scope.getMenus = function(){
        	//先获取餐别信息
//      	$scope.getPeriod_time();
        	//获取菜谱信息
        	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templatePlans?startTime="+$scope.rangeStartDate+"&endTime="+$scope.rangeEndDate,'',"GET",
        			function(data){
        				console.log(data);
			 			if( data.code == 0){
			 					$scope.menus = data.data;
			 					$scope.intial = $scope.menus.concat();
			 					$scope.filterDatas( $scope.rangeStartDate, $scope.intial);
//			 					$scope.auditResultWeek();
			 			}else{
			 				console.log(data.msg);
			 			}
			 		});
        }
        	$scope.classNum = '';
        	//获取食堂下所有分类
   			$scope.getCategorys = function(){
   				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/categorys",'',"GET",function(data){
   							console.log(data);
				 			if( data.code == 0){
				 					$scope.classify = data.data;  
				 					if( $scope.classify != null){
				 						$scope.classNum = $scope.classify.length;
				 						 //第1行的总宽度
				        				$scope.oneLineNum = 2 + $scope.totalTypes.length + $scope.classNum ;
				        				console.log($scope.oneLineNum);
				 					}
				 			}else{
				 				console.log(data.msg);
				 			}
				 		});
   			}
   			//获取某食堂下所有菜品
   			$scope.getDishes = function(){
   				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/items",'',"GET",function(data){
				 			if( data.code == 0){
				 					$scope.classDishes = data.data;  
				 					$scope.dishesByOneCategory = $scope.classDishes ;
									$scope.intialOneCategory = $scope.classDishes ;
				 					//$scope.classintial = data.data ;
    								//$scope.classcurrentData = data.data ;
				 			}else{
				 				console.log(data.msg);
				 			}
				 		});
   			}
   			 //点击属性，时时查询菜品
        $scope.searchAttributeDishes = function(){
        	$scope.cardInfor = '';
//      	console.log($scope.classify);
        	console.log($scope.methods);
//			console.log($("input[name='category']:checked").val());
			var category = $("input[name='category']:checked").val();
			if(  category == undefined){
				category ='';
			}
//			console.log($("input[name='method']:checked").val());
			var method = $("input[name='method']:checked").val();
			if(  method == undefined){
				method ='';
			}else{
				console.log($scope.methods[0].gcode)
				method = $scope.methods[0].gcode + $("input[name='method']:checked").val() ;
			}
//      	console.log($scope.tastes);
//      	console.log($scope.colors);
//      	console.log($scope.shapes);
			
			var arrTastes = $scope.tastes.concat() ;
			var postTastes = [];
			for( var i = 0;i<arrTastes.length ; i++){
				if(arrTastes[i].checked ){
					postTastes.push(arrTastes[i].gcode + arrTastes[i].id);
				}
			}
			var arrColors = $scope.colors.concat() ;
			var postarrColors = [];
			for( var i = 0;i<arrColors.length ; i++){
				if(arrColors[i].checked ){
					console.log(arrColors[i]);
					postarrColors.push(arrColors[i].gcode + arrColors[i].id);
				}
			}
			var arrShapes = $scope.shapes.concat() ;
			var postarrShapes = [];
			for( var i = 0;i<arrShapes.length ; i++){
				if(arrShapes[i].checked){
					postarrShapes.push(arrShapes[i].gcode +arrShapes[i].id);
				}
			}
			
        	var postData = {
        		"categoryId":category,
        		"cook":method,
        		"tastes":postTastes,
        		"colors":postarrColors,
        		"shapes":postarrShapes,
        	}
        	console.log(postData);
        	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/itemList",postData,"POST",function(data){
				 			console.log(data);
				 			if( data.code == 0){
				 					$scope.classDishes = data.data;  
				 					$scope.dishesByOneCategory = $scope.classDishes ;
									$scope.intialOneCategory = $scope.classDishes ;
									//清空模糊查询框
									$scope.cardInfor = ''
									if( data.data ==null){
										$scope.showError(data.msg);
									}
				 				
				 			}else{
				 				$scope.showError(data.msg);
				 			}
				 		});
        	
        }
        
   			 //清空选项
        $scope.clearAttribute = function(){
        	$("input[name='category']").removeAttr('checked');
        	$("input[name='method']").removeAttr('checked');
        	var post1 = $scope.tastes;
        	for(var i = 0;i<post1.length;i++){
        		post1[i].checked = false;
        	}
        	var post2 = $scope.colors;
        	for(var i = 0;i<post2.length;i++){
        		post2[i].checked = false;
        	}
        	var post3 = $scope.shapes;
        	for(var i = 0;i<post3.length;i++){
        		post3[i].checked = false;
        	}
        	$scope.cardInfor = '';
        	$scope.searchAttributeDishes();
        }
   			$scope.canteenId =  $scope.getCanteenId() ;
        if( $scope.getCanteenId() != ''){
   				$scope.canteenId =  $scope.getCanteenId() ;
   				//先获取餐别信息
        		$scope.getPeriod_time();
		 		 $scope.getTemplates();
		 		 $scope.getCategorys();//查询菜品分类
		 		 //$scope.getDishes();//查询所有菜品
		 		 //获取某食堂下所有菜谱计划
		 		 $scope.getMenus();
		 		 $scope.clearAttribute();
		 		 
   			}
		   	$scope.$on('to-child', function(event,data) {
						 //获取从父控制器传来的当前选中食堂
						$scope.canteenId = data;
						//先获取餐别信息
        				$scope.getPeriod_time();
				 		$scope.getTemplates();
				 		$scope.getCategorys();//查询菜品分类
		 				//$scope.getDishes();//查询所有菜品
		 				//获取某食堂下所有菜谱计划
				 		$scope.getMenus();
				 		$scope.clearAttribute();
				 		
				});
   			var content = '';
   			var content2 = '';
   			
   			$scope.templeChange = function(){
   					content = '';
   					content2 = '';
   					$scope.maDatas = [];
	   				var arr = [];
	   				$scope.searchDishes();
   			}
   			 //$scope.excelTableName = '山东财经大学食堂菜单'+'('+$scope.rangeStartDate+' - '+$scope.rangeEndDate+')';
   			//按日期过滤数据
   			$scope.filterDatas = function(startDate,datas){
   				var today = $scope.getNowFormatDate();
   				var arr = datas;
   				var arrPeriods = $scope.periods.concat();
   				var newList = [[],[],[],[],[],[],[]];
   				for(var i = 0; i<newList.length ; i++){
   					for(var j=0; j<arrPeriods.length; j++){
   						newList[i].push(arrPeriods[j]);
   						newList[i].pointed_date = $scope.getDisDate(startDate,i);
   						var hanzi = '一';
   						if( i == 0 ){
   							hanzi = '一'
   						}
   						if( i == 1 ){
   							hanzi = '二'
   						}
   						if( i == 2 ){
   							hanzi = '三'
   						}
   						if( i == 3 ){
   							hanzi = '四'
   						}
   						if( i == 4 ){
   							hanzi = '五'
   						}
   						if( i == 5 ){
   							hanzi = '六'
   						}
   						if( i == 6 ){
   							hanzi = '日'
   						}
   						newList[i].dateFormat = '星期'+hanzi+'    ('+$scope.getDisDate(startDate,i)+')';
   					}
   				}
   				for(var i = 0; i<arr.length ; i++){
   					if( $scope.distance_days( arr[i].pointed_date,startDate) == 0 ){
						for(var m = 0 ;m < newList[0].length ; m++){
							if( arr[i].period_time_id ==  newList[0][m].period_time_id){
								newList[0][m] = arr[i];
							}
						}
   					}
   					if( $scope.distance_days( arr[i].pointed_date,startDate) == 1 ){
						for(var m = 0 ;m < newList[1].length ; m++){
							if( arr[i].period_time_id ==  newList[1][m].period_time_id){
								newList[1][m] = arr[i];
							}
						}
   					}
   					if( $scope.distance_days( arr[i].pointed_date,startDate) == 2 ){
						for(var m = 0 ;m < newList[2].length ; m++){
							if( arr[i].period_time_id ==  newList[2][m].period_time_id){
								newList[2][m] = arr[i];
							}
						}
   					}
   					if( $scope.distance_days( arr[i].pointed_date,startDate) == 3 ){
						for(var m = 0 ;m < newList[3].length ; m++){
							if( arr[i].period_time_id ==  newList[3][m].period_time_id){
								newList[3][m] = arr[i];
							}
						}
   					}
   					if( $scope.distance_days( arr[i].pointed_date,startDate) == 4 ){
						for(var m = 0 ;m < newList[4].length ; m++){
							if( arr[i].period_time_id ==  newList[4][m].period_time_id){
								newList[4][m] = arr[i];
							}
						}
   					}
   					if( $scope.distance_days( arr[i].pointed_date,startDate) == 5 ){
						for(var m = 0 ;m < newList[5].length ; m++){
							if( arr[i].period_time_id ==  newList[5][m].period_time_id){
								newList[5][m] = arr[i];
							}
						}
   					}
   					if( $scope.distance_days( arr[i].pointed_date,startDate) == 6 ){
						for(var m = 0 ;m < newList[6].length ; m++){
							if( arr[i].period_time_id ==  newList[6][m].period_time_id){
								newList[6][m] = arr[i];
							}
						}
   					}
   				}
   				$scope.menus = newList ;
   				 $scope.excelTableName = $scope.corporation+'('+$scope.rangeStartDate+' - '+$scope.rangeEndDate+')'
   				console.log($scope.menus);
   			}
   			//$scope.filterDatas($scope.rangeStartDate,$scope.intial);
   			$scope.menuId= '';
   			$scope.judgeDate = false;
   			$scope.pointed_date = $scope.rangeStartDate.concat();
   			$scope.period_time_id = '';
   			$scope.planId = '';
   			//打开单个模板
 			$scope.showMenu = function(pointed_date,period_time_id,planId,end_time){//id,orderindex
 				
 				$scope.clickShowleft();
// 				if( $scope.classify.length != 0){
// 					 //打开模板时，默认展示第1种分类种的菜品
//      			$scope.getDishesByCategory($scope.classify[0].id);
// 				}
 				$scope.pointed_date = pointed_date ;
 				$scope.period_time_id = period_time_id ;
 				$scope.planId = planId ;
 				$('#time1').val('');
 				$('#time2').val('');
 				$('#reserve').val('');
 				$('#chargeback').val('');
 				$scope.template_id = '';
 				$('#dishText').text('');
 				content = '';
// 				//判断时间是否已过
   				var distance = $scope.distance_days(pointed_date,$scope.getNowFormatDate());
				if(distance >= 0){
					$scope.judgeDate = false ;
				}else{
					$scope.judgeDate = true ;
				}
   				//循环调取所有菜谱信息，匹配今天的菜谱信息，赋值
   				if( planId == undefined){//说明点开的计划没有内容，点击确定时，调取新建
   					if( $scope.templates.length != 0){
   						$scope.template_id = $scope.templates[0].id;
   					}
   					if( $scope.templates.length <= 1){
   						$scope.templeChange();
   					}
   					var periodArr =  $scope.periods ;//餐别信息
   					for( var i =0;i<periodArr.length ; i++){
   						
   						if(periodArr[i].period_time_id == period_time_id){
   							$('#time1').val(periodArr[i].start_time);
			 				$('#time2').val(periodArr[i].end_time);
			 				$('#reserve').val(periodArr[i].book_end_time);
			 				$('#chargeback').val(periodArr[i].refund_end_time);
   						}
   					}
   					$scope.maDatas = [];
   					console.log($scope.maDatas);
   				}else{
   					console.log(6666);
   					var arr = $scope.menus;
   					for( var i = 0 ;i<arr.length ; i++){
   						for( var j=0;j<arr[i].length;j++){
   							if(arr[i][j].id == planId){
   								$('#time1').val(arr[i][j].start_time);
   								$('#time2').val(arr[i][j].end_time);
   								$('#reserve').val(arr[i][j].reserve);
   								$('#chargeback').val(arr[i][j].chargeback);
   								$scope.template_id = arr[i][j].template_id ;
   								$scope.maDatas = arr[i][j].items.concat() ;
   								var resultArr = arr[i][j].items ;
   								for( var k = 0; k < resultArr.length ; k++){
   									if( k == (resultArr.length -1) ){
				   						content += resultArr[k].name ;
				   					}else{
				   						content += resultArr[k].name +',' ;
				   					}
   								}
   								$('#dishText').text(content);
   							}
   						}
   					}
   				}
   				$('#menuEdit').modal('toggle');
   			}
 			$scope.checkTemples = [];
 			$scope.judgeType = '0';//默认是新增	
 			//新增同时先去核查
 			$scope.checkOut_true = function(){
 				$scope.judgeType = '0';//设置为新增核查模式
 				if( isNull( $('#time1').val() ) == true){
           			$scope.showError('开始时间不能为空');
           			return;
           		}
   				if( isNull( $('#time2').val() ) == true){
           			$scope.showError('结束时间不能为空');
           			return;
           		}
   				if( isNull( $('#reserve').val() ) == true){
           			$scope.showError('结束预定不能为空');
           			return;
           		}
   				if( isNull( $('#chargeback').val() ) == true){
           			$scope.showError('结束退订不能为空');
           			return;
           		}
   				if( $scope.maDatas.length == 0){
   					$scope.showError('已选菜肴不能为空');
           			return;
   				}
   				var arr = $scope.maDatas;
   				for(var i= 0;i<arr.length;i++){
   					if(arr[i].count <= 0 || arr[i].count >=1000){
   						$scope.showError('菜肴数量需在0~1000之间');
           				return;
   					}
   				}
   				//如果没有计划id，就是新增
//				if( $scope.planId == undefined){//说明是新增
					var postData = {
								"canteen_id": $scope.canteenId,
								"period_time_id":$scope.period_time_id,//餐别id
								"pointed_date": $scope.pointed_date,
								"start_time": $('#time1').val(),//开始时间
								"end_time": $('#time2').val(),//结束时间
								"reserve": $('#reserve').val(),//结束预定
								"chargeback": $('#chargeback').val(),//结束退订
								//"template_id": $scope.template_id,//所选模板id
								"items": $scope.maDatas//菜品
							}
			        	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/menuPlanAudit",postData,"POST",
			            	function(data){
					 			if( data.code == 0){
					 				$('#checkTemple').show();
					 				$scope.checkTemples = data.data;
					 				console.log($scope.checkTemples);
					 			}else{
					 				console.log(data.msg);
					 			}
				 		});
//				}
//				else{//是修改
//					var postData = {
//								"canteen_id": $scope.canteenId,
//								"period_time_id":$scope.period_time_id,//餐别id
//								"pointed_date": $scope.pointed_date,
//								"start_time": $('#time1').val(),
//								"end_time": $('#time2').val(),
//								"reserve": $('#reserve').val(),
//								"chargeback": $('#chargeback').val(),
//								//"template_id": $scope.template_id,
//								"items": $scope.maDatas
//							}
//					console.log(postData);
//			        	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templatePlan/"+$scope.planId,postData,"PUT",
//			            	function(data){
//					 			console.log(data);  
//					 			if( data.code == 0){
//					 				$scope.getMenus();
//									$('#menuEdit').modal('toggle');
//					 			}else{
//					 				console.log(data.msg);
//					 			}
//				 		});
//				}
 			}
 			//展开统一核查模板
			$scope.openCheck = function(){
				$("#planCheck").modal('toggle');
			}
			//统一核查确认去核查按钮
			$scope.check_true = function(){
				$scope.judgeType = '1';//设置为统一核查入口模式
				var arr = $scope.periods;
				var postPeriods = [];
				for( var i = 0 ;i<arr.length;i++){
					if( arr[i].checked){
						postPeriods.push(arr[i].period_time_id);
					}
				}
				if( isNull( $('#checkDay').val() ) == true ){
           			$scope.showError('请选择核查日期');
           			return;
           		}
				if( postPeriods.length == 0){
           			$scope.showError('请选择餐别');
           			return;
           		}
				var postData = {
					'selectDay':$('#checkDay').val() ,
					'ptIds':postPeriods
				}
				console.log(postData);
				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/MenuPlanAuditOneDay",postData,"POST",
				            	function(data){
						 			console.log(data);  
						 			if( data.code == 0){
						 				$('#checkTemple').show();
						 				$scope.checkTemples = data.data;
						 			}else{
						 				$scope.showError(data.msg);
						 			}
					 		});
			}
   			//核查展示模板确定键
   			$scope.menuEdit_true = function(){
   				if($scope.judgeType == '1' ){
   					$('#checkTemple').hide();
 					$("#planCheck").modal('toggle');
 					return;
   				}
   				if( isNull( $('#time1').val() ) == true){
           			$scope.showError('开始时间不能为空');
           			return;
           		}
   				if( isNull( $('#time2').val() ) == true){
           			$scope.showError('结束时间不能为空');
           			return;
           		}
   				if( isNull( $('#reserve').val() ) == true){
           			$scope.showError('结束预定不能为空');
           			return;
           		}
   				if( isNull( $('#chargeback').val() ) == true){
           			$scope.showError('结束退订不能为空');
           			return;
           		}
   				if( $scope.maDatas.length == 0){
   					$scope.showError('已选菜肴不能为空');
           			return;
   				}
   				var arr = $scope.maDatas;
   				for(var i= 0;i<arr.length;i++){
   					if(arr[i].count <= 0){
   						$scope.showError('菜肴数量必须大于0');
           				return;
   					}
   				}
   				//如果没有计划id，就是新增
				if( $scope.planId == undefined){//说明是新增
					var postData = {
								"canteen_id": $scope.canteenId,
								"period_time_id":$scope.period_time_id,//餐别id
								"pointed_date": $scope.pointed_date,
								"start_time": $('#time1').val(),//开始时间
								"end_time": $('#time2').val(),//结束时间
								"reserve": $('#reserve').val(),//结束预定
								"chargeback": $('#chargeback').val(),//结束退订
								//"template_id": $scope.template_id,//所选模板id
								"items": $scope.maDatas,//菜品
								"times":1
							}
			        	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templatePlan",postData,"POST",
			            	function(data){
					 			console.log(data);  
					 			if( data.code == 0){
									$('#menuEdit').modal('toggle');
									$('#checkTemple').hide();
									$scope.getMenus();
					 			}else if(data.code == 100){
					 				$scope.errorM = data.msg
					 				$('#checkTemple').hide();
					 				$('#confirmSame').modal('toggle')
					 			}else{
					 				$scope.showError(data.msg);
					 			}
				 		});
				}else{//是修改
					var postData = {
								"canteen_id": $scope.canteenId,
								"period_time_id":$scope.period_time_id,//餐别id
								"pointed_date": $scope.pointed_date,
								"start_time": $('#time1').val(),
								"end_time": $('#time2').val(),
								"reserve": $('#reserve').val(),
								"chargeback": $('#chargeback').val(),
								//"template_id": $scope.template_id,
								"items": $scope.maDatas
							}
			        	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templatePlan/"+$scope.planId,postData,"PUT",
			            	function(data){
					 			if( data.code == 0){
					 				$scope.getMenus();
									$('#menuEdit').modal('toggle');
									$('#checkTemple').hide();
					 			}else{
					 				$scope.showError(data.msg);
					 			}
				 		});
				}
   			}
   			//尽管菜品重复坚持提交
   			$scope.sureSame = function(){
   				$('#confirmSame').modal('toggle')
   				var postData = {
						"canteen_id": $scope.canteenId,
						"period_time_id":$scope.period_time_id,//餐别id
						"pointed_date": $scope.pointed_date,
						"start_time": $('#time1').val(),//开始时间
						"end_time": $('#time2').val(),//结束时间
						"reserve": $('#reserve').val(),//结束预定
						"chargeback": $('#chargeback').val(),//结束退订
						//"template_id": $scope.template_id,//所选模板id
						"items": $scope.maDatas,//菜品
						"times":2
					}
			        	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templatePlan",postData,"POST",
			            	function(data){
					 			console.log(data);  
					 			if( data.code == 0){
									$('#menuEdit').modal('toggle');
									$('#checkTemple').hide();
									$scope.getMenus();
					 			}else if(data.code == 100){
					 				$scope.errorM = data.msg
					 				$('#checkTemple').modal('toggle')
					 				$('#confirmSame').modal('toggle')
					 			}else{
					 				$scope.showError(data.msg);
					 			}
				 		});
   			}
   			//核查展示模板取消键
 			$scope.menuEdit_false = function(){
 				if( $scope.judgeType == '1' ){
 					$("#planCheck").modal('toggle');
 					$('#checkTemple').hide();
 				}else{
 					$('#checkTemple').hide();
 				}
 				
 			}
   			//展开取消发布模板询问框
   			$scope.cancelPublish = function(){
   				$("#delPlan").modal('toggle');
   			}
   			//取消发布的确定键
   			$scope.del_plan = function(){
   					$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/templatePlan/"+$scope.planId,'',"DELETE",
			            	function(data){
					 			if( data.code == 0){
					 				$scope.getMenus();
					 				$("#delPlan").modal('toggle');
									$('#menuEdit').modal('toggle');
					 			}else{
					 				console.log(data.msg);
					 			}
				 		});
   			}
   			//展示左模板
   			$scope.clickShowleft = function(){
   				$('#leftTmeple').addClass('div_active');
   				$('#rightTmeple').removeClass('div_active');
   				$('#box1').show();
   				$('#box2').hide();
   			}
   			//展示右模板
   			$scope.clickShowright = function(){
   				$('#rightTmeple').addClass('div_active');
   				$('#leftTmeple').removeClass('div_active');
   				$('#box2').show();
   				$('#box1').hide();
   			}
   			//选择菜肴
//		$scope.smallCategorys = [];
//		$scope.intialSmallCategory =[];
		$scope.intialOneCategory = [];
//      //根据点选的分类名称，获取该分类下所有菜品
//		$scope.getDishesByCategory = function(id){
//			var arr = $scope.classDishes ;
//			var newList = [];
//			for(var i = 0 ;i<arr.length ; i++){
//				if(arr[i].category_id == id){
//					newList.push(arr[i]);
//				}
//			}
//			$scope.dishesByOneCategory = newList ;
//			$scope.intialOneCategory = newList ;
//		}
       
        //物料查询初始值默认为 ‘’
        $scope.goods = '';
       
        //实时监控物料查询搜索框的值
            $scope.$watch('cardInfor',  function() {
            	if($scope.cardInfor ==undefined){
            		$scope.cardInfor = '';
            	}
		           //准备一个空的数组
		           var newList = [];
		           var arr = $scope.intialOneCategory ;
		           var length = arr.length;
		           	for(var i=0;i<length;i++){
						if(  arr[i].name.indexOf($scope.cardInfor) >= 0 ){
							newList.push(arr[i]);
						}
		           }
		          $scope.dishesByOneCategory =  newList ;
            });
            
        //菜肴管理中删除此行
        $scope.delThis = function(event,name){
        	event.stopPropagation();
        	var target = event.target;
        	var arr = $scope.maDatas.concat() ;
			 for(var i=0; i<arr.length; i++) {
			    if(arr[i].name == name) {
			      arr.splice(i, 1);
			      break;
			    }
			  }
			 $scope.maDatas = arr.concat() ;
			 content2 = '';
			 for(var j=0;j<arr.length;j++){
			 	if( j == (arr.length -1) && j!= 0){
					content2 += arr[j].name ;
				}else if(j == 0 && content !='' && j != (arr.length -1)){
					content2 += ',' + arr[j].name + ',' ;
				}else if(j == 0 && content !='' && j == (arr.length -1)){
					content2 += ',' + arr[j].name ;
				}else if(j == 0 && content ==''){
					content2 += arr[j].name + ',' ;
				}else{
					content2 += arr[j].name +',' ;
				}
			 }
			 $('#dishText').text(content2);
        }
        //点击菜品添加
        $scope.cmaterial = function(event,id,name,unit){
        	event.stopPropagation();
        	var standards = document.getElementsByClassName('maDataList_name');
        	var intial = '0';//默认标准成分模板中没有
//      	var currentContent = $('#dishText').text();
        	for(var i = 0; i< standards.length ; i++){
        		if(standards[i].innerHTML == name){
        			intial = '1'; //如果模板中已经有这个成分了 就置为1
        		}
        	}
        	if( intial == '0'){//说明模板中没有，需要添加material_id
        		$scope.maDatas.push( { "id": id,"name": name, "unit":unit, "count":1});
			}
        	var arr = $scope.maDatas ;
        	content2 = '';
        	 for(var j=0;j<arr.length;j++){
			 	if( j == (arr.length -1) && j!= 0){
					content2 += arr[j].name ;
				}else if(j == 0 && content !='' && j != (arr.length -1)){
					content2 += ',' + arr[j].name + ',' ;
				}else if(j == 0 && content !='' && j == (arr.length -1)){
					content2 += ',' + arr[j].name ;
				}else if(j == 0 && content ==''){
					content2 += arr[j].name + ',' ;
				}else{
					content2 += arr[j].name +',' ;
				}
			 }
			 $('#dishText').text(content2);
        }
        
        //晒选模板的展开与隐藏
        $scope.toggleSaixuan = function(){
        	$('#saixuan').slideToggle("slow");
        }
        //菜谱及核查的综合结果集
        $scope.itemAndAudit = [];
        //查询一周核查结果
        $scope.auditResultWeek = function(){
        	$scope.itemAndAudit = [];
        	//v1/menus/canteens/{cid}/MenuPlanAuditOneWeek
        	
        	var periodTime = $scope.periods ;
        	var arrpp = [];
        	for( var i = 0 ; i< periodTime.length ; i++){
        		arrpp.push(periodTime[i].period_time_id);
        	}
        	var postData = {
        		'startDate':$scope.rangeStartDate,
        		'endDate':$scope.rangeEndDate,
        		'ptIds':arrpp
        	}
        	console.log(postData);
        	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/doExport",postData,"POST",function(data){
				 			console.log(data);
				 			if( data.code == 0){
				 				$scope.itemAndAudit = data.data;	
				 			}else{
				 				//$scope.showError(data.msg);
				 			}
		 				$timeout(function(){
								$scope.download('resultExport','食堂菜单',$scope.rangeStartDate+'至'+$scope.rangeEndDate);
							},1000);
				 		});
        }
        //$scope.auditResultWeek();
        
        //导出表格
        $scope.resultTotalExport = function(){
        	$scope.auditResultWeek();
        }
       
       
		
   }])
   
	//智能发布
   .controller('intelPublishCtrl', ['$scope', '$timeout','$routeParams',function ($scope, $timeout,$routeParams) {
   	$(".modal-dialog").draggable();//为模态对话框添加拖拽
        $(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动
         //日历选择
			$('#datepicker').datepicker({
			  autoclose: true
			});
			$('#datepicker2').datepicker({
			  autoclose: true
			});
   		$scope.mealStyles = [];
   		$scope.mealStyle ='';
   		$scope.classify = [];
   		$scope.dishesInfors = [];
   		$scope.intelPublish = [];
   		//查询某一食堂下所有餐别信息
        $scope.getPeriod_time = function(){
        	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/base_system/canteens/"+$scope.canteenId+"/periodTimes",'',"GET",
        			function(data){
			 			if( data.code == 0){
			 					$scope.mealStyles = data.data;
			 					if( data.data.length != 0){
			 						$scope.mealStyle = $scope.mealStyles[0].period_time_id ;
			 					}
			 			}else{
			 				console.log(data.msg);
			 			}
			 		});
        }
        	//获取食堂下所有分类
   			$scope.getCategorys = function(){
   				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/categorys",'',"GET",function(data){
				 			if( data.code == 0){
				 					$scope.classify = data.data;  
				 					var arr = $scope.classify ;
				 					for(var i = 0; i< arr.length ; i++){
				 						arr[i].totalNum = 0;
				 						arr[i].fixedItems = [];
				 						arr[i].balanceNum = 0;
				 						arr[i].release_mode = 0;
				 					}
				 					$scope.intelPublish = arr;
				 			}else{
				 				console.log(data.msg);
				 			}
				 		});
   			}
   			//获取某食堂下所有菜品
   			$scope.getDishes = function(){
   				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/items",'',"GET",function(data){
				 			if( data.code == 0){
				 					$scope.dishesInfors = data.data;  
				 			}else{
				 				console.log(data.msg);
				 			}
				 		});
   			}
        if( $scope.getCanteenId() != ''){
   				$scope.canteenId =  $scope.getCanteenId() ;
		 		 $scope.getPeriod_time();
		 		 $scope.getCategorys();//查询菜品分类
		 		 $scope.getDishes();//查询所有菜品
   			}
		   	$scope.$on('to-child', function(event,data) {
						 //获取从父控制器传来的当前选中食堂
						$scope.canteenId = data;
				 		$scope.getPeriod_time();
				 		$scope.getCategorys();//查询菜品分类
		 				$scope.getDishes();//查询所有菜品
				});
				
				
   		//获取当前时间(年月日)
        $scope.getNowFormatDate = function() {
		    var date = new Date();
		    var seperator1 = "-";
		    var seperator2 = ":";
		    var month = date.getMonth() + 1;
		    var strDate = date.getDate();
		    if (month >= 1 && month <= 9) {
		        month = "0" + month;
		    }
		    if (strDate >= 0 && strDate <= 9) {
		        strDate = "0" + strDate;
		    }
		    var now = date.getFullYear() + seperator1 + month + seperator1 + strDate;
		    return now;
		}
		$('#datepicker').val($scope.getNowFormatDate());
		$('#datepicker2').val($scope.getNowFormatDate());
//		$('#reservation').daterangepicker();
//		$scope.searchDate = $scope.getNowFormatDate()+' '+'至'+' '+$scope.getNowFormatDate();
		$scope.dishs = [];			    
		//点击更改集合里的发布方式，并改变样式			    
		$scope.clickButton = function(id,event,type){
			event.stopPropagation();
			var target = event.target ;
			var arr = jQuery(target).siblings();
			for(var i = 0;i<arr.length;i++){
				$(arr[i]).removeClass('mychoice');
			}
			
			var arrtt = $scope.intelPublish.concat();
			for(var j = 0;j<arrtt.length;j++){
				if(arrtt[j].id == id){
					arrtt[j].release_mode = type ;
				}
			}
			jQuery(target).addClass('mychoice');
		}
		//改变发布总数量
		$scope.change = function(id){
			//剩余发布数量根据前面的值实时改变
			//$('#remain_'+id).text( $('#totalNum_'+id).val());
			var arrtt = $scope.intelPublish.concat();
			for(var j = 0;j<arrtt.length;j++){
				//输入大于总数，则赋总数
				if(arrtt[j].id == id ){
					if( $('#totalNum_'+id).val() < arrtt[j].fixedItems.length){
						$('#totalNum_'+id).val( arrtt[j].fixedItems.length );
						$scope.intelPublish[j].balanceNum = 0;
					}else if( ($('#totalNum_'+id).val() - arrtt[j].count ) > 0  ){
						$('#totalNum_'+id).val(arrtt[j].count);
						$scope.intelPublish[j].balanceNum = arrtt[j].count - arrtt[j].fixedItems.length ;
					}else{
						$scope.intelPublish[j].balanceNum = $('#totalNum_'+id).val() - arrtt[j].fixedItems.length ;
					}
					var temp = $('#totalNum_'+id).val();
					var temp2 = temp.replace(/\D/g,'');
					$('#totalNum_'+id).val(temp2);
				}
			}
		}
		$scope.categoryName = '';
		//打开固定选择菜品模板
		$scope.openSelectDishs = function(id,event,name){
			$scope.categoryName = name ;
			event.stopPropagation();
			$('#selectDishs').modal('toggle');
			//$scope.dishs = [];			    
			var newlist =[];
			var arr = $scope.dishesInfors ;
			for(var i = 0 ;i<arr.length ;i++){
				if($scope.dishesInfors[i].category_id == id){
					if( $scope.dishesInfors[i].checked == undefined){
						$scope.dishesInfors[i].checked = false;
					}
					newlist.push($scope.dishesInfors[i]);
				}
			}
			$scope.dishs = newlist ;
		}
		//点选菜品
		$scope.checkDish = function(categoryid,id,name){
			var arr = $scope.dishs.concat();
			var totalArr = $scope.intelPublish.concat();
			var newlist = [];
			var str1  = '';
			for( var i = 0;i<arr.length ;i++){
				if( arr[i].checked == true){
					newlist.push(arr[i]);
					str1 += arr[i].name + ',';
				}
			}
			for( var j = 0;j<totalArr.length ;j++ ){
				if( totalArr[j].id == categoryid){
					if( newlist.length > $('#totalNum_'+categoryid).val() ){
						//$('#totalNum_'+categoryid).val(newlist.length) ;
						//$scope.intelPublish[j].balanceNum = newlist.length - newlist.length ;
						$scope.intelPublish[j].fixedItems = newlist ;
						$scope.intelPublish[j].totalNum = newlist.length ;
						$scope.intelPublish[j].balanceNum = 0 ;
					}else{
						$scope.intelPublish[j].fixedItems = newlist ;
						$scope.intelPublish[j].balanceNum = $('#totalNum_'+categoryid).val() - newlist.length ;
					}
				}
			}
			$('#choicedDish_'+categoryid).val(str1);
		}
		//点击保存
		$scope.toPublish = function(){
			if( $('#datepicker').val() == '' || $('#datepicker').val() == null){
				$scope.showError('请添加发布起始时间');
			}
			if( $('#datepicker2').val() == '' || $('#datepicker2').val() == null){
				$scope.showError('请添加发布结束时间');
			}
			if( $('#datepicker').val() > $('#datepicker2').val()){
				$scope.showError('发布起始时间应该小于等于结束时间');
			}
			var str = $scope.searchDate ;
//			var start_time = str.substr(0,10) ;
//			var end_time = str.substr(13,10)
			var weekStr = '';
			var planWeekend = '0';
			$('input[name="planWeekend"]:checked').each(function(){
				weekStr += $(this).val();
			});
			if(weekStr == ''){
				planWeekend = '0';
			}else if(weekStr == '0'){
				planWeekend = '1';
			}else if(weekStr == '1'){
				planWeekend = '2';
			}else if(weekStr == '01'){
				planWeekend = '3';
			}
			var postData = {
							canteenId : $scope.canteenId ,//食堂id
							periodTimeId : $scope.mealStyle ,//餐别id
							start_time : $('#datepicker').val() ,//起始时间
							end_time : $('#datepicker2').val(), //结束时间
							planWeekend : planWeekend , //周末排单
							dishes: $scope.intelPublish //固定菜品
							//dishes:[]
						}
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/templates/release",postData,"PUT",function(data){
				 			if( data.code == 0){
				 				$scope.showSuccess('操作成功！');
				 			}else{
				 				if( data.msg == null ){
				 					$scope.showError('操作失败');
				 				}else{
				 					$scope.showError(data.msg);
				 				}
				 			}
				 		});
		}
   }])
   //套餐管理
   .controller('packageManageCtrl', ['$scope', '$timeout','$routeParams',function ($scope, $timeout,$routeParams) {
   	$(".modal-dialog").draggable();//为模态对话框添加拖拽
        $(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动
   		$scope.intial = [];
   		$scope.dishesInfors = [];
   		$scope.currentData = [];
   		$scope.categorys = [];
   		$scope.dishesChoiced = [];
   		$scope.categroyId = '';
   		$scope.windows = [];
   		$scope.chiefs = [];
   		$scope.packageId = '';
   		$scope.packageName = '';
   		$scope.is_fixed_package = false;
   		$scope.groupId = '';
   		$scope.groupName = '';
   		$scope.available_choose_count = 0;
   		//获取食堂下所有档口
		$scope.getWindows = function(){
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/base_system/canteens/"+$scope.canteenId+"/windows",'',"GET",function(data){
			 			if( data.code == 0){
			 					$scope.windows = data.data;
			 					$scope.window = $scope.windows[0].id;
			 			}else{
			 				console.log(data.msg);
			 			}
			 		});
		}
		//获取所有厨师
		$scope.getChiefs = function(){
			$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/chief",'',"GET",function(data){
			 			if( data.code == 0){
			 					$scope.chiefs = data.data;
			 					$scope.chief = $scope.chiefs[0].id;
			 			}else{
			 				console.log(data.msg);
			 			}
			 		});
		}
   		//获取食堂下所有分类
   			$scope.getCategorys = function(){
   				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/categorys",'',"GET",function(data){
				 			if( data.code == 0){
				 					$scope.categorys = data.data;
				 					if( $scope.categorys.length != 0){
				 						$scope.categoryId = $scope.categorys[0].id;
				 					}
				 			}else{
				 				console.log(data.msg);
				 			}
				 		});
   			}
   			//查询食堂下所有套餐
   			$scope.getPackages = function(){
   				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/packages",'',"GET",function(data){
				 			if( data.code == 0){
				 					$scope.packages = data.data;  
				 					$scope.packageId = '' ;
				 					$scope.groups = [];//将套餐中组的信息也清空
			 						$scope.groupId = '';
			 						$scope.Group_details = [];
				 			}else{
				 				console.log(data.msg);
				 			}
				 		});
   			}
   			//获取某食堂下所有菜品
   			$scope.getDishes = function(){
   				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/items",'',"GET",function(data){
				 			if( data.code == 0){
				 					$scope.dishesInfors = data.data;  
				 					$scope.intial = data.data ;
    								$scope.currentData = data.data ;
				 			}else{
				 				console.log(data.msg);
				 			}
				 		});
   			}
   			if( $scope.getCanteenId() != ''){
   				$scope.canteenId =  $scope.getCanteenId() ;
   				//获取某食堂下所有分类
		 		$scope.getCategorys();
		 		//获取所有菜品
		 		$scope.getDishes();
		 		//获取所有档口
		 		$scope.getWindows(); 
		 		//获取所有厨师
				$scope.getChiefs();
				$scope.getPackages();
   			}
		   	$scope.$on('to-child', function(event,data) {
						 //获取从父控制器传来的当前选中食堂
						$scope.canteenId = data;
						//获取某食堂下所有分类
				 		$scope.getCategorys();
				 		//获取所有菜品
				 		$scope.getDishes();
				 		//获取所有档口
		 				$scope.getWindows(); 
		 				//获取所有厨师
						$scope.getChiefs();
						$scope.getPackages();
				});
   		$scope.groups = [];
   		
	   	//套餐编辑		  
	   	$scope.pockageEdit = function(event){
	   		event.stopPropagation();
	   		$("#packageEdit").modal('toggle');
	   	}
	   	//点击菜品分类
	   	$scope.clickCategory = function(event,id){
	   		$scope.categroyId = id;
	   		event.stopPropagation();
	   		var arr = $scope.dishesInfors ;
	   		var list = [];
	   		for(var i =0;i<arr.length;i++){
	   			if(arr[i].category_id == id){
	   				list.push(arr[i]); 
	   			}
	   		}
	   		$scope.currentData = list ;
	   	}
	   	//点击全部菜品
	   	$scope.clickAllCategory = function(){
	   		$scope.currentData = $scope.dishesInfors.concat();
	   	}
	   	//选择菜品
	   	$scope.moveDish = function(event,id){
	   		event.stopPropagation();
	   		var arrCurrent = $scope.currentData ;
	   		var arr = $scope.dishesInfors ;
//	   		var arrChoiced = $scope.dishesChoiced ;
//	   		for(var j =0;j<arrChoiced.length;j++){
//	   			if( arrChoiced[j].id == id ){
//	   					$scope.showError('菜品已选择');
//	           			return;
//	   			}
//	   		}
	   		//向选择菜品集合中添加信息
	   		for(var i =0;i<arr.length;i++){
	   			if(arr[i].id == id){
	   				$scope.dishesChoiced.push(arr[i]); 
	   				//从总备选菜品库中剔除菜品
	   				$scope.dishesInfors.splice(i, 1);
	   			}
	   		}
	   		//当前分类备选信息也跟着剔除
	   		for(var i =0;i<arrCurrent.length;i++){
	   			if(arrCurrent[i].id == id){
	   				$scope.currentData.splice(i, 1);
	   			}
	   		}
	   	}
   		
   			//取字符串中汉字首字母方法
			$scope.getPingyin = function(packageName){
				$scope.shortName = makePy(packageName);
			}
			$scope.getPingyin_up = function(up_packageName){
				$scope.up_shortName = makePy(up_packageName);
			}
			//生成套餐条码
			$scope.packageCode = new Date().getTime();//默认的条码
			$scope.packagePrice = 0;
			$scope.quickDish = false ;
         	$scope.is_fixed_package = false ;
             //打开新增套餐模板
            $scope.addPackage = function(){
            	$scope.packageNo ='';
            	$scope.packageCode = new Date().getTime();
            	$scope.packageName = '';
            	$scope.shortName = '';
            	$scope.packagePrice = 0;
            	$scope.quickDish = false;
            	$scope.is_fixed_package = false;
            	$scope.description = '';
            	$("#addPackage").modal('toggle');
            }
            //新增模板中，确定按钮
            $scope.addPackage_true = function(){
            	
            	//保存校验
//         		if( isNull($scope.packageNo+'') == true){
//         			$scope.showError('套餐编码不能为空');
//         			return;
//         		}
           		if( isNull($scope.packageCode+'') == true){
           			$scope.showError('套餐条码不能为空');
           			return;
           		}
           		if( ($scope.packageCode+'').length > 16){
           			$scope.showError('套餐条码长度不能大于16');
           			return;
           		}
           		if( isNull($scope.packageName) == true){
           			$scope.showError('套餐名称不能为空');
           			return;
           		}
           		if( $scope.packageName.length > 20){
           			$scope.showError('套餐名称长度不能大于20');
           			return;
           		}
           		if( isNull($scope.shortName) == true){
           			$scope.showError('套餐助记码不能为空');
           			return;
           		}
           		if( $scope.shortName.length > 10){
           			$scope.showError('套餐助记码长度不能大于10');
           			return;
           		}
           		if( isNull($scope.packagePrice) == true){
           			$scope.showError('套餐价格不能为空');
           			return;
           		}
           		if( $scope.packagePrice<=0 ){
           			$scope.showError('套餐价格必须大于0');
           			return;
           		}
           		if( $scope.packagePrice>=1000 ){
           			$scope.showError('套餐价格必须小于1000');
           			return;
           		}
           		if( $scope.description.length > 100){
           			$scope.showError('套餐描述长度不能大于100');
           			return;
           		}
            	var postData = {
								"window_id": $scope.window,
								"category_id": $scope.categoryId,
								"name": $scope.packageName,
								"code": $scope.packageCode,//编码
								"assist_code":$scope.shortName,
								"barcode": $scope.packageCode,//条码
								"description": $scope.description,
								"price": $scope.packagePrice,
								"is_shortcut": $scope.quickDish,
								"is_fixed_package": $scope.is_fixed_package,
								"user_id": $scope.chief,
								//"unit_id":"1" //套餐默认单位就是  份（套餐） 即单位unit_id = 1
							}
            	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/packages",postData,"POST",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$("#addPackage").modal('toggle');
			 				$scope.getPackages();
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
            	
            }
            //点击套餐修改按钮
            $scope.updatePackage = function(){
            	if( $scope.packageId == ''){
        			$('#contentHtml').html('请选择套餐');
					$('#warningChoose').modal('toggle');
					return;
            	}
            	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/packages/"+$scope.packageId,'',"GET",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.up_packageNo =data.data.code;//编码
			            	$scope.up_packageCode = data.data.barcode;//条码
			            	$scope.up_categoryId = data.data.category_id;//分类id
			            	$scope.up_packageName = data.data.name;//套餐名称
			            	$scope.up_shortName = data.data.assist_code;//助记码
			            	$scope.up_packagePrice = data.data.price;//套餐价格
			            	$scope.up_quickDish = data.data.is_shortcut;//是否为快捷菜品
			            	$scope.up_is_fixed_package = data.data.is_fixed_package;//是否为固定套餐
			            	$scope.up_window = data.data.window_id;//制作档口
			            	$scope.up_chief = data.data.user_id;//制作厨师
			            	$scope.up_description = data.data.description;//描述
			 			}else{
			 				console.log(data.msg);
			 			}
		 		});
            	$("#updatePackage").modal('toggle')
            }
          	//修改套餐模板的确定按钮
          	$scope.updatePackage_true = function(){
//        		//保存校验
//         		if( isNull($scope.up_packageNo) == true){
//         			$scope.showError('套餐编码不能为空');
//         			return;
//         		}
           		if( isNull($scope.up_packageCode) == true){
           			$scope.showError('套餐条码不能为空');
           			return;
           		}
           		if( ($scope.packageCode+'').length > 16){
           			$scope.showError('套餐条码长度不能大于16');
           			return;
           		}
           		if( isNull($scope.up_packageName) == true){
           			$scope.showError('套餐名称不能为空');
           			return;
           		}
           		if( $scope.up_packageName.length > 20){
           			$scope.showError('套餐名称长度不能大于20');
           			return;
           		}
           		if( isNull($scope.up_shortName) == true){
           			$scope.showError('套餐助记码不能为空');
           			return;
           		}
           		if( $scope.up_shortName.length > 10){
           			$scope.showError('套餐助记码长度不能大于10');
           			return;
           		}
           		if( isNull($scope.up_packagePrice) == true){
           			$scope.showError('套餐价格不能为空');
           			return;
           		}
           		if( $scope.up_packagePrice<=0 ){
           			$scope.showError('套餐价格必须大于0');
           			return;
           		}
           		if( $scope.up_packagePrice>=1000 ){
           			$scope.showError('套餐价格必须小于1000');
           			return;
           		}
           		if( $scope.up_description.length > 100){
           			$scope.showError('套餐描述长度不能大于100');
           			return;
           		}
            	//类别名称有值后，调取后台修改套餐方法
            	var postData = {
            					"canteen_id": $scope.canteenId,
								"window_id": $scope.up_window,
								"category_id": $scope.up_categoryId,
								"name": $scope.up_packageName,
								"code": $scope.up_packageCode,//编码
								"assist_code":$scope.up_shortName,
								"barcode": $scope.up_packageCode,//条码
								"description": $scope.up_description,
								"price": $scope.up_packagePrice,
								"is_shortcut": $scope.up_quickDish,
								"is_fixed_package": $scope.up_is_fixed_package,
								"user_id": $scope.up_chief,
								"unit_id":"1" //套餐默认单位就是  份（套餐） 即单位unit_id = 1
							}
            	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/packages/"+$scope.packageId,postData,"PUT",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$("#updatePackage").modal('toggle')
			 				$scope.getPackages();
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
          	}
          	//默认启用停用键显示启用
          	$scope.is_enabled = false;
          	//停用套餐
          	$scope.enablePackage = function(){
          		if( $scope.packageId == ''){
        			$('#contentHtml').html('请选择套餐');
					$('#warningChoose').modal('toggle');
					return;
            	}
            	$scope.getJson($scope.resultPath+'/wisdomeatery/v1/menus/canteens/'+$scope.canteenId+'/packages/'+$scope.packageId+'?stop=true',{},"PUT",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$scope.is_enabled = false;
			 				$scope.getPackages();
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
          	}
          	//启用套餐
          	$scope.disablePackage = function(){
          		if( $scope.packageId == ''){
        			$('#contentHtml').html('请选择套餐');
					$('#warningChoose').modal('toggle');
					return;
            	}
            	$scope.getJson($scope.resultPath+'/wisdomeatery/v1/menus/canteens/'+$scope.canteenId+'/packages/'+$scope.packageId+'?enable=true',{},"PUT",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$scope.is_enabled = true;
			 				$scope.getPackages();
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
          	}
          	//点击删除按钮
          	$scope.delPackage = function(){
          		if( $scope.packageId == ''){
        			$('#contentHtml').html('请选择套餐');
					$('#warningChoose').modal('toggle');
					return;
            	}
          		$("#delPackage").modal('toggle')
          	}
          	//查询套餐中的分组数据
          	$scope.getChoosedPackageDetails = function(){
          		$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/packages/"+$scope.packageId+"/package_groups",'',"GET",
		            	function(data){
				 			if( data.code == 0){
				 				$scope.groups = data.data;
				 				$scope.groupId = '';
				 			}else{
				 				console.log(data.msg);
				 			}
			 		});
          	}
	   			
           	 //删除套餐
            $scope.del_Package = function(){
				$scope.getJson($scope.resultPath+'/wisdomeatery/v1/menus/canteens/'+$scope.canteenId+'/packages/'+$scope.packageId,{},"DELETE",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$("#delPackage").modal('toggle')
			 				$scope.getPackages();
			 				
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
            }
            
            //查询套餐中分组
   		$scope.getGroups = function(event,packageId,is_enabled,is_fixed_package,packageName){
   			$scope.groupId = '';
   			$scope.Group_details = [];
   			if( is_enabled == 1){
   				$scope.is_enabled = true ;
   			}else{
   				$scope.is_enabled = false ;
   			}
   			$scope.packageId = packageId ;
   			$scope.is_fixed_package = is_fixed_package ;
   			$scope.packageName = packageName ;
   			event.stopPropagation();
// 			var target = event.target ;
   			$('#package_'+packageId).siblings().each(function(){
   				$(this).css('background-color','#ffffff');
   			});
   			$('#package_'+packageId).css('background-color','#e4eaec');
   			//查询指定分组数据
   			$scope.getChoosedPackageDetails();
   		}
   			//打开新增分组模板
   			$scope.addGroups = function(){
   				console.log($scope.packageId);
   				if( $scope.packageId == ''){
   					$scope.showError('请选择套餐');
           			return;
   				}
   				if( $scope.is_fixed_package == true){
   					$scope.fixedGroupName = '';
   					$("#addFixedGroup").modal('toggle');
   				}else{
   					$scope.randomGroupName = '';
   					$scope.available_choose_count = 0;
   					$("#addRandomGroup").modal('toggle');
   				}
   			}
   			//新增固定分组
   			$scope.addFixed_true = function(){
   				if( isNull($scope.fixedGroupName) == true){
           			$scope.showError('分组名称不能为空');
           			return;
           		}
   				var postData = {
								"name": $scope.fixedGroupName,
								"available_choose_count": 1 ,
							}
            	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/packages/"+$scope.packageId+"/package_groups",postData,"POST",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$("#addFixedGroup").modal('toggle');
			 				//查询指定分组数据
			 				$scope.getChoosedPackageDetails();
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
   			}
   			//新增随机分组
   			$scope.addRandom_true = function(){
   				if( isNull($scope.randomGroupName) == true){
           			$scope.showError('分组名称不能为空');
           			return;
           		}
   				if( isNull($scope.available_choose_count) == true){
           			$scope.showError('可选数量不能为空');
           			return;
           		}
   				if( $scope.available_choose_count >= 1000 || $scope.available_choose_count  <=0){
           			$scope.showError('可选数量应在0~1000之间');
           			return;
           		}
   				var postData = {
								"name": $scope.randomGroupName,
								"available_choose_count": $scope.available_choose_count ,
							}
            	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/packages/"+$scope.packageId+"/package_groups",postData,"POST",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$("#addRandomGroup").modal('toggle');
			 				//查询指定分组数据
			 				$scope.getChoosedPackageDetails();
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
   			}
   			//查询分组明细
   			$scope.getGroupDetails = function(){
   				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/packages/"+$scope.packageId+"/package_groups/"+$scope.groupId+"/package_group_details",'',"GET",
		            	function(data){
				 			if( data.code == 0){
				 				$scope.Group_details = data.data.concat();
				 				$scope.maDatas = data.data.concat();
				 			}else{
				 				console.log(data.msg);
				 			}
			 		});
   			}
   			//点击分组获取分组资料
   			$scope.getGroup_details = function(event,groupId,name,available_choose_count){
   				event.stopPropagation();
   				console.log(groupId);	
   				console.log(name);	
   				console.log(available_choose_count);	
   				$scope.groupId = groupId;
		   		$scope.groupName =name;
		   		$scope.available_choose_count = available_choose_count;
		   	
		   		var target = event.target ;
		   		if(target.nodeName == 'SPAN'){
		   			target = target.parentNode;
		   		}
	   			$(target).siblings().each(function(){
	   				$(this).css('background-color','#ffffff');
	   			});
	   			$(target).css('background-color','#e4eaec');
	   			$scope.getGroupDetails();
   			}
   			//打开分组编辑模板
   			$scope.updateGroups = function(){
   				if( $scope.groupId == ''){
        			$('#contentHtml').html('请选择分组');
					$('#warningChoose').modal('toggle');
					return;
            	}
   				if( $scope.is_fixed_package == true){
   					$scope.updatefixedGroupName = $scope.groupName ;
   					$("#updateFixedGroup").modal('toggle');
   				}else{
   					$scope.updaterandomGroupName = $scope.groupName ;
   					$scope.updateavailable_choose_count = $scope.available_choose_count;
   					$("#updateRandomGroup").modal('toggle');
   				}
   			}
   			//固定分组编辑
   			$scope.updateFixed_true = function(){
   				if( isNull($scope.updatefixedGroupName) == true){
           			$scope.showError('分组名称不能为空');
           			return;
           		}
   				var postData = {
								"name": $scope.updatefixedGroupName,
								"available_choose_count": 1 ,
							}
            	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/packages/"+$scope.packageId+"/package_groups/"+$scope.groupId,postData,"PUT",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$("#updateFixedGroup").modal('toggle');
			 				//查询指定分组数据
				   			$scope.getChoosedPackageDetails();
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
   			}
   			//随机分组编辑
   			$scope.updateRandom_true = function(){
   				if( isNull($scope.updaterandomGroupName) == true){
           			$scope.showError('分组名称不能为空');
           			return;
           		}
   				if( isNull($scope.updateavailable_choose_count) == true){
           			$scope.showError('可选数量不能为空');
           			return;
           		}
   				if( $scope.updateavailable_choose_count >= 1000 || $scope.updateavailable_choose_count  <=0){
           			$scope.showError('可选数量应在0~1000之间');
           			return;
           		}
   				var postData = {
								"name": $scope.updaterandomGroupName,
								"available_choose_count": $scope.updateavailable_choose_count ,
							}
            	$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/packages/"+$scope.packageId+"/package_groups/"+$scope.groupId,postData,"PUT",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$("#updateRandomGroup").modal('toggle');
			 				//查询指定分组数据
				   			$scope.getChoosedPackageDetails();
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
   			}
   			//删除分组
   			$scope.delGroup = function(){
   				if( $scope.groupId == ''){
        			$('#contentHtml').html('请选择分组');
					$('#warningChoose').modal('toggle');
					return;
            	}
   				$("#delGroup").modal('toggle');
   			}
   			$scope.del_Group = function(){
   				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/menus/canteens/"+$scope.canteenId+"/packages/"+$scope.packageId+"/package_groups/"+$scope.groupId,'',"DELETE",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$("#delGroup").modal('toggle');
			 				//查询指定分组数据
				   			$scope.getChoosedPackageDetails();
			 			}else{
			 				$scope.showError(data.msg);
			 			}
		 		});
   			}
   			
   			
            //打开选择菜品模板
            $scope.openDishSelect = function(){
            	if( $scope.groupId == ''){
        			$('#contentHtml').html('请选择分组');
					$('#warningChoose').modal('toggle');
					return;
            	}
//          	$scope.maDatas = [];
            	if( $scope.is_fixed_package == true ){
            		$("#choiceDishes").modal('toggle')
            	}else{
            		$("#choiceDishesRandom").modal('toggle')
            	}
            }
            $scope.intialOneCategory = [];
          //根据点选的分类名称，获取该分类下所有菜品
			$scope.getDishesByCategory = function(id){
				var arr = $scope.intial ;
				var newList = [];
				for(var i = 0 ;i<arr.length ; i++){
					if(arr[i].category_id == id){
						newList.push(arr[i]);
					}
				}
				$scope.dishesByOneCategory = newList ;
				$scope.intialOneCategory = newList ;
			}
			//点击菜品添加
	        $scope.cmaterial = function(event,id,name,unit){
	        	event.stopPropagation();
	        	var standards = document.getElementsByClassName('maDataList_name');
	        	var intial = '0';//默认标准成分模板中没有
	//      	var currentContent = $('#dishText').text();
	        	for(var i = 0; i< standards.length ; i++){
	        		if(standards[i].innerHTML == name){
	        			intial = '1'; //如果模板中已经有这个成分了 就置为1
	        		}
	        	}
	        	if( intial == '0'){//说明模板中没有，需要添加material_id
//	        		if( $scope.is_fixed_package == true){
//	        			this.maDatas.push( { "item_id": id,"name": name, "unit":unit, "count":0});
//	        		}else{
	        			this.maDatas.push( { "item_id": id,"item_name": name, "unit_name":unit, "count":1});
//	        		}
				}
	        }
	 		$scope.maDatas = [];
	 		//菜肴管理中删除此行
	        $scope.delThis = function(event,name){
	        	
	        	event.stopPropagation();
	        	var target = event.target;
	        	var arr = $scope.maDatas ;
	        	console.log(arr);
	        	console.log(name);
				 for(var i=0; i<arr.length; i++) {
				    if(arr[i].item_name == name) {
				      arr.splice(i, 1);
				      break;
				    }
				  }
				 $scope.maDatas = arr ;
	        }
	        //分组中菜品明细批量添加
	        $scope.addDish_true = function(){
	        	var arr = $scope.maDatas ;
	        	for( var i = 0;i<arr.length ;i++){
	        		if( isNull(arr[i].count) == true  ){
	        			$scope.showError('数量不能为空');
	        			return;
	        		}
	        		if( arr[i].count <= 0  ){
	        			$scope.showError('数量必须大于0');
	        			return;
	        		}
	        		if( arr[i].count >= 1000  ){
	        			$scope.showError('数量只能小于1000');
	        			return;
	        		}
	        	}
	        	$scope.getJson($scope.resultPath+'/wisdomeatery/v1/menus/canteens/'+$scope.canteenId+'/packages/'+$scope.packageId+"/package_groups/"+$scope.groupId+"/package_group_details/batch",$scope.maDatas,"POST",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				if( $scope.is_fixed_package == true){
			 					$("#choiceDishes").modal('toggle');
			 				}else{
			 					$("#choiceDishesRandom").modal('toggle');
			 				}
			 				
			 				//重新查询分组明细
			 				$scope.getGroupDetails();
			 			}else{
			 				console.log(data.msg);
			 			}
		 		});
	        }
	        $scope.dish_name = '';
	        $scope.dish_id = '';
	        //删除某个菜品
            $scope.dish_del = function(id,name){
            	$scope.dish_id = id;
            	$scope.dish_name = name;
            	
            	$('#delDish').modal('toggle');
            }
            $scope.delDish_true = function(){
            	$scope.getJson($scope.resultPath+'/wisdomeatery/v1/menus/canteens/'+$scope.canteenId+'/packages/'+$scope.packageId+"/package_groups/"+$scope.groupId+"/package_group_details/"+$scope.dish_id,'',"DELETE",
	            	function(data){
			 			if( data.code == 0){
			 				$scope.showSuccess('操作成功！');
			 				$('#delDish').modal('toggle');
			 				//重新查询分组明细
			 				$scope.getGroupDetails();
			 			}else{
			 				console.log(data.msg);
			 			}
		 		});
            }
             //实时监控物料查询搜索框的值
            $scope.$watch('cardInfor',  function() {
            	if($scope.cardInfor ==undefined){
            		$scope.cardInfor = '';
            	}
		           //准备一个空的数组
		           var newList = [];
		           var arr = $scope.intialOneCategory ;
		           var length = arr.length;
		           	for(var i=0;i<length;i++){
						if(  arr[i].name.indexOf($scope.cardInfor) >= 0 ){
							newList.push(arr[i]);
						}
		           }
		          $scope.dishesByOneCategory =  newList ;
            });
            
            
            
            
            
            
            //回退菜品
// 		$scope.removeDish = function(event,id){
// 			event.stopPropagation();
//	   		var arrCurrent = $scope.currentData ;
//	   		var arr = $scope.dishesInfors ;
//	   		var arrChoiced = $scope.dishesChoiced ;
//	   		//向总菜品库中添加信息
//	   		for(var i =0;i<arrChoiced.length;i++){
//	   			if(arrChoiced[i].id == id){
//	   				console.log(arrChoiced[i]);
//	   				//总菜品库中添加回退的菜品信息
//	   				$scope.dishesInfors.push(arrChoiced[i]); 
//	   				//如果回退的菜品为当前分类中的菜品，也添加菜品信息
//	   				if( arrChoiced[i].category_id == $scope.categroyId){
//	   					$scope.currentData.push(arrChoiced[i]); 
//	   				}
//	   				//从已选菜品库中剔除菜品
//	   				$scope.dishesChoiced.splice(i, 1);
//	   			}
//	   		}
//	   		console.log($scope.dishesInfors);
// 		}
   		
   	
   }])
   
//测试登录rsa加密
   .controller('angularloginCtrl', ['$scope', '$timeout','$routeParams',function ($scope, $timeout,$routeParams) {
   	
   	
   		$scope.mysubmit = function(){
     		//var mykey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCjoOB8FVgKgk6kDu1HgHX7dkpLuboQlfonThHXXXXU2yJI/Tj1Bk4DC22xb/1gTz1W4TIdh6/JGtrU5FQ6UhYResPDF4sRBgE7IjuxY9MHEXRF8hXK5y9laNt6pYGK4QE8wr7SSpuXc+jP0DNfjmqHVZooPh3+rgGUMVYnNYAxdwIDAQAB';
     		//var mykey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDzlPSe7u+6KF5IRgbCIJc2qiONvLy3/0QZwlhHLrLBoRRfzPZyhEsmJXGc+GVtiGTxsQxsorkfyLBjWjUNDbb22UeSe9O9Au80L+DRbgFORYRwm2l/UYlC0UNN8Uzvc28ve7SzNm1r5bL1Xaxpb0nrB35YdM0vPdDD/HYcjHHuowIDAQAB';
      		
      		var username = $('#username').val();
      		var password = $('#password').val();
//  		var str1 = '{ "name": "cxh", "sex": "man" }'; 
 			//var myll = {'loginName':'gly','loginPwd':'123456'};
//		    var mydate = JSON.stringify(myll);
			var testStr = {'loginName':username,'loginPwd':password};
//		    var testStr = {'loginName':'yubin','loginPwd':'哈空间都会发空间发挥'};
		    //var testStr = {'loginName':'yubin','loginPwd':'天生我才必有用千金散尽还复来7349872934729834729834729873492837498273498274982734987239847238947298347289347298472983479823749823749823479823748923749823748934728934789237498273568739867943875983748364587236587236458726587236458723645726345987263457896234975623849568972345682734658237456598589347598347589375983754983745897395873498572938475983284576'};
		   
//		    var arr1 = new Array();
//		    console.log(arr1);
//		    var arr2 = new Array();
//		    console.log(arr2);
//		    var newArr = arr1.concat(arr2);
//		    console.log(newArr);
//		    return;
//  		 var encrypt = new JSEncrypt();
//	         encrypt.setPublicKey(mykey);
//	         var encrypted = encrypt.encrypt(mydate);
			//var encrypted = $scope.encrypt(myll);
	          //var resultData = {'callerId':'OFFLINE_SERVICE','data':encrypted};
			// console.log(resultData);
//			 ?debug=true
	   		$scope.getJson('http://192.168.1.108:8080/wisdomeatery/localserv/v1/test',$scope.encrypt(testStr),"POST",function(data){
	   			console.log(data);
	   			
	   			//localStorage.loginId = data.content.loginId ;
	   			//localStorage.name = data.content.name ;
	   			//$scope.jump('/cardManage');
	   		});

   		}
   	
   }])